当前位置: 首页>>代码示例>>C#>>正文


C# Progress.Report方法代码示例

本文整理汇总了C#中System.Progress.Report方法的典型用法代码示例。如果您正苦于以下问题:C# Progress.Report方法的具体用法?C# Progress.Report怎么用?C# Progress.Report使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Progress的用法示例。


在下文中一共展示了Progress.Report方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ExtractInstallFiles

        public async Task ExtractInstallFiles(Action<int> progressCallback)
        {
            if (_casc == null)
                return;

            IProgress<int> progress = new Progress<int>(progressCallback);

            await Task.Run(() =>
            {
                var installFiles = _casc.Install.GetEntries("Windows");
                var build = _casc.Config.BuildName;

                int numFiles = installFiles.Count();
                int numDone = 0;

                foreach (var file in installFiles)
                {
                    EncodingEntry enc;

                    if (_casc.Encoding.GetEntry(file.MD5, out enc))
                        _casc.SaveFileTo(enc.Key, Path.Combine("data", build, "install_files"), file.Name);

                    progress.Report((int)(++numDone / (float)numFiles * 100));
                }
            });
        }
开发者ID:WoW-Tools,项目名称:CASCExplorer,代码行数:26,代码来源:CASCViewHelper.cs

示例2: Application

        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //  Task.Factory.StartNewWithProgress(
            // X:\jsc.svn\core\ScriptCoreLib.Async\ScriptCoreLib.Async\Extensions\TaskAsyncExtensions.cs

            Native.css.style.transition = "background-color 300ms linear";

            // future jsc will allow a background thread to directly talk to the DOM, while creating a callsite in the background
            IProgress<string> set_backgroundColor = new Progress<string>(yield);

            var g = new
            {
                yield,
                colors = new
                {
                    white = "white",
                    yellow = "yellow",
                    cyan = "cyan"
                }
            };

            //var colors = new { yellow = "yellow", cyan = "cyan" };

            new IHTMLButton { "invoke" }.AttachToDocument().onclick +=
                async e =>
                {
                    await Task.Run(async delegate
                    {
                        // we could also support direct delegates?

                        set_backgroundColor.Report(g.colors.yellow);

                        // the .css thing is under our control is it not. could be the first to get special support
                        //Native.css.style.backgroundColor = "red";

                        await Task.Delay(1000);

                        set_backgroundColor.Report(g.colors.cyan);
                    });
                    await Task.Delay(1000);
                    set_backgroundColor.Report(g.colors.white);
                };
        }
开发者ID:exaphaser,项目名称:JSC-Cross-Compiler,代码行数:47,代码来源:Application.cs

示例3: ExtractInstallFiles

        public async Task ExtractInstallFiles(Action<int> progressCallback)
        {
            if (_casc == null)
                return;

            IProgress<int> progress = new Progress<int>(progressCallback);

            await Task.Run(() =>
            {
                var installFiles = _casc.Install.GetEntries("Windows");
                var build = _casc.Config.BuildName;

                int numFiles = installFiles.Count();
                int numDone = 0;

                foreach (var file in installFiles)
                {
                    _casc.ExtractFile(_casc.Encoding.GetEntry(file.MD5).Key, "data\\" + build + "\\install_files", file.Name);

                    progress.Report((int)(++numDone / (float)numFiles * 100.0f));
                }
            });
        }
开发者ID:aeo24,项目名称:WoWMap,代码行数:23,代码来源:CASCViewHelper.cs

示例4: TryBeginFolderLoadAsync

        // out parameters can't be used in anonymous methods, so a separate pointer to backgroundWorker is required for return to the caller
        private async Task<bool> TryBeginFolderLoadAsync(FolderLoad folderLoad)
        {
            List<FileInfo> filesToAdd = folderLoad.GetFiles();
            if (filesToAdd.Count == 0)
            {
                // no images were found in folder; see if user wants to try again
                MessageBox messageBox = new MessageBox("Select a folder containing images or videos?", this, MessageBoxButton.YesNo);
                messageBox.Message.Problem = "There aren't any images or videos in the folder '" + this.FolderPath + "' so your image set is currentl empty.";
                messageBox.Message.Reason = "\u2022 This folder has no images in it (files ending in .jpg)." + Environment.NewLine;
                messageBox.Message.Reason += "\u2022 This folder has no videos in it (files ending in .avi or .mp4).";
                messageBox.Message.Solution = "Choose Yes and select a folder containing images and/or videos or choose No and add files later via the File menu.";
                messageBox.Message.Hint = "\u2022 The files may be in a subfolder of this folder." + Environment.NewLine;
                messageBox.Message.Hint += "\u2022 If you need to set the image set's time zone before adding files choose No." + Environment.NewLine;
                messageBox.Message.StatusImage = MessageBoxImage.Question;
                if (messageBox.ShowDialog() == false)
                {
                    return false;
                }

                IEnumerable<string> folderPaths;
                if (this.ShowFolderSelectionDialog(out folderPaths))
                {
                    folderLoad.FolderPaths.Clear();
                    folderLoad.FolderPaths.AddRange(folderPaths);
                    return await this.TryBeginFolderLoadAsync(folderLoad);
                }

                // exit if user changed their mind about trying again
                return false;
            }

            // update UI for import (visibility is inverse of RunWorkerCompleted)
            this.FeedbackControl.Visibility = Visibility.Visible;
            this.FileNavigatorSlider.Visibility = Visibility.Collapsed;
            IProgress<FolderLoadProgress> folderLoadStatus = new Progress<FolderLoadProgress>(this.UpdateFolderLoadProgress);
            FolderLoadProgress folderLoadProgress = new FolderLoadProgress(filesToAdd.Count, this.MarkableCanvas.Width > 0 ? (int)this.MarkableCanvas.Width : (int)this.Width);
            folderLoadStatus.Report(folderLoadProgress);
            if (this.state.SkipDarkImagesCheck)
            {
                this.statusBar.SetMessage("Loading folders...");
            }
            else
            {
                this.statusBar.SetMessage("Loading folders (if this is slower than you like and dark image detection isn't needed you can select Skip dark check in the Options menu right now)...");
            }
            this.FileViewPane.IsActive = true;

            // Load all files found
            // First pass: Examine files to extract their basic properties and build a list of files not already in the database
            //
            // With dark calculations enabled:
            // Profiling of a 1000 image load on quad core, single 80+MB/s capable SSD shows the following:
            // - one thread:   100% normalized execution time, 35% CPU, 16MB/s disk (100% normalized time = 1 minute 58 seconds)
            // - two threads:   55% normalized execution time, 50% CPU, 17MB/s disk (6.3% normalized time with dark checking skipped)
            // - three threads: 46% normalized execution time, 70% CPU, 20MB/s disk
            // This suggests memory bound operation due to image quality calculation.  The overhead of displaying preview images is fairly low; 
            // normalized time is about 5% with both dark checking and previewing skipped.
            //
            // For now, try to get at least two threads as that captures most of the benefit from parallel operation.  Video loading may be more CPU bound 
            // due to initial frame rendering and benefit from additional threads.  This requires further investigation.  It may also be desirable to reduce 
            // the pixel stride in image quality calculation, which would increase CPU load.
            //
            // With dark calculations disabled:
            // The bottleneck's the SQL insert though using more than four threads (or possibly more threads than the number of physical processors as the 
            // test machine was quad core) results in slow progress on the first 20 files or so, making the optimum number of loading threads complex as it
            // depends on amortizing startup lag across faster progress on the remaining import.  As this is comparatively minor relative to SQL (at least
            // for O(10,000) files for now just default to four threads in the disabled case.
            //
            // Note: the UI thread is free during loading.  So if loading's going slow the user can switch off dark checking asynchronously to speed up 
            // loading.
            //
            // A sequential partitioner is used as this keeps the preview images displayed to the user in pretty much the same order as they're named,
            // which is less confusing than TPL's default partitioning where the displayed image jumps back and forth through the image set.  Pulling files
            // nearly sequentially may also offer some minor disk performance benefit.
            List<ImageRow> filesToInsert = new List<ImageRow>();
            TimeZoneInfo imageSetTimeZone = this.dataHandler.FileDatabase.ImageSet.GetTimeZone();
            await Task.Run(() => Parallel.ForEach(
                new SequentialPartitioner<FileInfo>(filesToAdd),
                Utilities.GetParallelOptions(this.state.SkipDarkImagesCheck ? Environment.ProcessorCount : 2), 
                (FileInfo fileInfo) =>
                {
                    ImageRow file;
                    if (this.dataHandler.FileDatabase.GetOrCreateFile(fileInfo, imageSetTimeZone, out file))
                    {
                        // the database already has an entry for this file so skip it
                        // if needed, a separate list of files to update could be generated
                        return;
                    }

                    BitmapSource bitmapSource = null;
                    try
                    {
                        if (this.state.SkipDarkImagesCheck)
                        {
                            file.ImageQuality = FileSelection.Ok;
                        }
                        else
                        {
                            // load bitmap and determine its quality
//.........这里部分代码省略.........
开发者ID:CascadesCarnivoreProject,项目名称:Timelapse,代码行数:101,代码来源:CarnassialWindow.xaml.cs

示例5: StartDoneButton_Click

        private async void StartDoneButton_Click(object sender, RoutedEventArgs e)
        {
            // This list will hold key / value pairs that will be bound to the datagrid feedback, 
            // which is the way to make those pairs appear in the data grid during background worker progress updates
            ObservableCollection<DateTimeRereadFeedbackTuple> feedbackRows = new ObservableCollection<DateTimeRereadFeedbackTuple>();
            this.FeedbackGrid.ItemsSource = feedbackRows;
            this.CancelButton.IsEnabled = false;
            this.StartDoneButton.Content = "_Done";
            this.StartDoneButton.Click -= this.StartDoneButton_Click;
            this.StartDoneButton.Click += this.DoneButton_Click;
            this.StartDoneButton.IsEnabled = false;

            IProgress<DateTimeRereadFeedbackTuple> rereadStatus = new Progress<DateTimeRereadFeedbackTuple>(this.ReportProgress);
            DateTimeRereadFeedbackTuple rereadProgress = new DateTimeRereadFeedbackTuple("Pass 1: Examining images and videos...", "Checking if dates/time differ");
            rereadStatus.Report(rereadProgress);
            await Task.Run(() =>
            {
                // check to see what date/times need updating
                List<ImageRow> filesToAdjust = new List<ImageRow>();
                int count = this.database.CurrentlySelectedFileCount;
                TimeZoneInfo imageSetTimeZone = this.database.ImageSet.GetTimeZone();
                for (int fileIndex = 0; fileIndex < count; ++fileIndex)
                {
                    ImageRow file = this.database.Files[fileIndex];
                    DateTimeOffset originalDateTime = file.GetDateTime();
                    string feedbackMessage = String.Empty;
                    try
                    {
                        DateTimeAdjustment dateTimeAdjustment = file.TryReadDateTimeOriginalFromMetadata(this.database.FolderPath, imageSetTimeZone);
                        if (dateTimeAdjustment == DateTimeAdjustment.None)
                        {
                            // couldn't read metadata, so get a candidate date/time from the file
                            file.SetDateTimeOffsetFromFileInfo(this.database.FolderPath, imageSetTimeZone);
                            feedbackMessage = "Using file date/time: ";
                        }
                        else if ((dateTimeAdjustment & DateTimeAdjustment.PreviousMetadata) == DateTimeAdjustment.PreviousMetadata)
                        {
                            feedbackMessage = "Using previous metadata date/time: ";
                        }
                        else
                        {
                            feedbackMessage = "Using metadata date/time: ";
                        }

                        DateTimeOffset rescannedDateTime = file.GetDateTime();
                        bool updateNeeded = false;
                        if (rescannedDateTime.Date == originalDateTime.Date)
                        {
                            feedbackMessage += "same date, ";
                        }
                        else
                        {
                            updateNeeded = true;
                            feedbackMessage += "different date, ";
                        }

                        if (rescannedDateTime.TimeOfDay == originalDateTime.TimeOfDay)
                        {
                            feedbackMessage += "same time, ";
                        }
                        else
                        {
                            updateNeeded = true;
                            feedbackMessage += "different time, ";
                        }

                        if (rescannedDateTime.Offset == originalDateTime.Offset)
                        {
                            feedbackMessage += "same UTC offset";
                        }
                        else
                        {
                            updateNeeded = true;
                            feedbackMessage += "different UTC offset";
                        }

                        if (updateNeeded)
                        {
                            filesToAdjust.Add(file);
                        }
                    }
                    catch (Exception exception)
                    {
                        Debug.Fail(String.Format("Unexpected exception processing '{0}'.", file.FileName), exception.ToString());
                        feedbackMessage += String.Format(" , skipping due to {0}: {1}.", exception.GetType().FullName, exception.Message);
                    }

                    if (fileIndex % Constant.ThrottleValues.SleepForImageRenderInterval == 0)
                    {
                        rereadProgress.FileName = file.FileName;
                        rereadProgress.Message = feedbackMessage;
                        rereadStatus.Report(new DateTimeRereadFeedbackTuple(file.FileName, feedbackMessage));
                        Thread.Sleep(Constant.ThrottleValues.RenderingBackoffTime); // Put in a delay every now and then, as otherwise the UI won't update.
                    }
                }

                // Pass 2. Update each date as needed 
                rereadProgress.FileName = String.Empty;
                rereadProgress.Message = String.Empty;
                rereadStatus.Report(rereadProgress);  // A blank separator
//.........这里部分代码省略.........
开发者ID:CascadesCarnivoreProject,项目名称:Timelapse,代码行数:101,代码来源:DateTimeRereadFromFiles.xaml.cs

示例6: Application

        static Application()
        {
            // inside worker?
            if (Native.document == null)
                return;



            // http://dejanglozic.com/tag/shadow-dom/

            Native.document.registerElement("x-work",
                async (IHTMLElement e) =>
                {
                    var s = e.createShadowRoot();


                    new IHTMLPre { "working... " + new { Thread.CurrentThread.ManagedThreadId } }.AttachTo(s);


                    new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachTo(s);

                    // first insertion point
                    new IHTMLContent { }.AttachTo(s);


                    new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachTo(s);



                    IProgress<string> worker_new_IHTMLPre = new Progress<string>(value => new IHTMLPre { value }.AttachTo(s));

                    var z = await Task.Run(
                        async delegate
                    {
                        // inside a worker thread now.

                        // can a worker talk to a shadow dom? :)
                        // perhaps if we expend our scope sharing?
                        // yet
                        // how would it look like to create a node in a worker?


                        //new IHTMLPre { "working... " + new { Thread.CurrentThread.ManagedThreadId } }.AttachTo(s);

                        for (int i = 0; i < 10; i++)
                        {
                            // look we are scope sharing
                            worker_new_IHTMLPre.Report(
                               "working... " + new { i, Thread.CurrentThread.ManagedThreadId }
                          );


                            await Task.Delay(500);
                            // did we resync scope fields?
                            // we got new data from attributes?
                        }




                        return 42;
                    }
                    );



                    new IHTMLPre { "working... done " + new { z } }.AttachTo(s);

                }
            );
        }
开发者ID:exaphaser,项目名称:JSC-Cross-Compiler,代码行数:71,代码来源:Application.cs

示例7: LoadEmployees

        private async void LoadEmployees()
        {
            CancellationTokenSource = new CancellationTokenSource();
            IProgress<double> progress = new Progress<double>(x => CurrentProgress = x);
            try {
                CurrentStatus = "Loading employees";

                Items.Clear();
                var result = await _dataProvider.LoadEmployeesAsync(CancellationTokenSource.Token, progress);

                if (result.Result != null) {
                    foreach (var item in result.Result) {
                        Items.Add(item);
                    }
                }
                if (result.Exception != null) {
                    throw result.Exception;
                }

                CurrentStatus = "Operation completed";
            }
            catch (OperationCanceledException) {
                CurrentStatus = "Operation cancelled";
            }
            catch (Exception ex) {
                CurrentStatus = "Operation failed - " + ex.Message;
            }
            finally {
                CancellationTokenSource.Dispose();
                CancellationTokenSource = null;
                progress.Report(0);
            }
        }
开发者ID:spudcz,项目名称:WpfAsyncData,代码行数:33,代码来源:MainViewModel.cs

示例8: TimerRun

        public async void TimerRun()
        {
            try 
	        {
                bool bRunning = false;
                await Task.Run(async () =>
                {
                    while (mbIsRunning == true)
                    {
                        bRunning = false; //Reset
                        await Task.Delay(1000);
                        foreach (Appliance appl in Appliances)
                        {
                            if (appl.IsRunning == true)
                            {
                                appl.Time = appl.Time.Add(new TimeSpan(0, 0, -1));

                                IProgress<object> progress = new Progress<object>(_ => ApplyTime(appl));
                                progress.Report(null);
                                bRunning = true;
                                progress = null;
                            }
                        }

                        //All timers have completed.  Why waste the cycles if we don't need to.... That's just rude.
                        if (bRunning == false) { mbIsRunning = false; }
                    }
                });
	        }
	        catch (Exception ex)
	        {
		        logException(ex);
	        }
        }
开发者ID:Blissgig,项目名称:ApplianceTMR,代码行数:34,代码来源:ATMREngine.cs

示例9: concatenateButton_Click

        private async void concatenateButton_Click(object sender, EventArgs e)
        {
            concatenateButton.Enabled = false;

            IProgress<string> progress_str = new Progress<string>(status =>
            {
                listBox1.Items.Add(status);
				listBox1.TopIndex = listBox1.Items.Count - 1;
            });

            try
            {
                IProgress<int> progress = new Progress<int>(percent =>
                {
                    progressBar1.Value = percent;
                });

                listBox1.Items.Clear();

                List<string> inFiles = new List<string>();
                inFiles.Add(openFileDialog1.FileName);
                inFiles.Add(openFileDialog2.FileName);
                if (inFile3CheckBox.Checked) inFiles.Add(openFileDialog3.FileName);
                if (inFile4CheckBox.Checked) inFiles.Add(openFileDialog4.FileName);

                await DoAsync(inFiles, saveFileDialog1.FileName, progress, progress_str);
            }
            catch
            {
                progress_str.Report("Exception caught processing files!");
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();

                concatenateButton.Enabled = true;
            }
        }
开发者ID:Evilpaul,项目名称:MHX-Concatenate,代码行数:39,代码来源:Form1.cs

示例10: tPhone_KeyPress

 private void tPhone_KeyPress(object sender, KeyPressEventArgs e)
 {
     if (e.KeyChar == (char)Keys.Return)
     {
         IProgress<Customer> customerProgess = new Progress<Customer>(
             c =>
             {
                 this.c = c;
                 ceView.tName.Text = c.Name;
                 ceView.tCompany.Text = c.Company;
                 ceView.tAddress.Text = c.Address;
                 ceView.tCity.Text = c.City;
                 ceView.tCountry.Text = c.Country;
                 ceView.tPostalCode.Text = c.PostalCode;
                 ceView.tPhone.Text = c.Phone;
                 ceView.tDoB.Value = c.DoB;
                 ceView.tID.Text = c.ID.ToString();
                 ceView.tEmail.Text = c.Email;
                 bPay.Click -= bPay_NoCustomer;
                 bPay.Click += bPay_Click;
             });
         new Loading("Loading customer",
             () =>
             {
                 var phone = tPhone.Text;
                 var phone2 = string.Format("1-{0}-{1}-{2}", phone.Substring(0, 3), phone.Substring(3, 3), phone.Substring(6));
     #if DEBUG
                 Console.WriteLine(phone2);
     #endif
                 uint cid = 0;
                 if (uint.TryParse("" + DB.Instance.SelectSingleValue("select id from customer where phone = '" + phone2 + "'"), out cid))
                 {
                     customerProgess.Report(new Customer(cid));
                 }
                 else
                 {
                     if (MessageBox.Show("No Customer Found!\nWould you like to rigister?", "Customer", MessageBoxButtons.YesNo) == DialogResult.Yes)
                     {
                         CustomerEdit ce = new CustomerEdit();
                         ce.tPhone.Text = phone2;
                         if ((new EditWindow(ce).ShowDialog()) == DialogResult.OK)
                         {
                             cid = (uint)DB.Instance.SelectSingleValue("select id from customer where phone = '" + phone2 + "'");
                             customerProgess.Report(new Customer(cid));
                         }
                     }
                 }
             });
     }
 }
开发者ID:redlive,项目名称:csis3275,代码行数:50,代码来源:Payment.cs

示例11: AnalyzeUnknownFiles


//.........这里部分代码省略.........
                            {
                                string name = row.Value.GetField<string>(2);

                                int type = row.Value.GetField<int>(1);

                                bool many = row.Value.GetField<int>(4) > 0;

                                for (int i = 3; i < 23; i++)
                                    idToName[row.Value.GetField<int>(i)] = "unknown\\sound\\" + name + (many ? "_" + (i - 2).ToString("D2") : "") + (type == 28 ? ".mp3" : ".ogg");
                            }
                        }
                    }

                    if (_casc.FileExists("DBFilesClient\\SoundKit.db2") && _casc.FileExists("DBFilesClient\\SoundKitEntry.db2"))
                    {
                        using (Stream skStream = _casc.OpenFile("DBFilesClient\\SoundKit.db2"))
                        using (Stream skeStream = _casc.OpenFile("DBFilesClient\\SoundKitEntry.db2"))
                        {
                            DB5Reader sk = new DB5Reader(skStream);
                            DB5Reader ske = new DB5Reader(skeStream);

                            Dictionary<int, List<int>> lookup = new Dictionary<int, List<int>>();

                            foreach (var row in ske)
                            {
                                int soundKitId = row.Value.GetField<int>(3);

                                if (!lookup.ContainsKey(soundKitId))
                                    lookup[soundKitId] = new List<int>();

                                lookup[soundKitId].Add(row.Value.GetField<int>(0));
                            }

                            foreach (var row in sk)
                            {
                                string name = row.Value.GetField<string>(0).Replace(':', '_');

                                int type = row.Value.GetField<byte>(12);

                                List<int> ske_entries;

                                if (!lookup.TryGetValue(row.Key, out ske_entries))
                                    continue;

                                bool many = ske_entries.Count > 1;

                                int i = 0;

                                foreach (var fid in ske_entries)
                                {
                                    idToName[fid] = "unknown\\sound\\" + name + (many ? "_" + (i + 1).ToString("D2") : "") + (type == 28 ? ".mp3" : ".ogg");
                                    i++;
                                }
                            }
                        }
                    }
                }

                CASCFolder unknownFolder = _root.GetEntry("unknown") as CASCFolder;

                if (unknownFolder == null)
                    return;

                IEnumerable<CASCFile> files = CASCFolder.GetFiles(unknownFolder.Entries.Select(kv => kv.Value), null, true);
                int numTotal = files.Count();
                int numDone = 0;

                WowRootHandler wowRoot = _casc.Root as WowRootHandler;

                foreach (var unknownEntry in files)
                {
                    CASCFile unknownFile = unknownEntry as CASCFile;

                    string name;
                    if (idToName.TryGetValue(wowRoot.GetFileDataIdByHash(unknownFile.Hash), out name))
                        unknownFile.FullName = name;
                    else
                    {
                        string ext = scanner.GetFileExtension(unknownFile);
                        unknownFile.FullName += ext;

                        if (ext == ".m2")
                        {
                            using (var m2file = _casc.OpenFile(unknownFile.Hash))
                            using (var br = new BinaryReader(m2file))
                            {
                                m2file.Position = 0x138;
                                string m2name = br.ReadCString();

                                unknownFile.FullName = "unknown\\" + m2name + ".m2";
                            }
                        }
                    }

                    progress.Report((int)(++numDone / (float)numTotal * 100));
                }

                _casc.Root.Dump();
            });
        }
开发者ID:WoW-Tools,项目名称:CASCExplorer,代码行数:101,代码来源:CASCViewHelper.cs

示例12: Play

        private void Play()
        {
            currentlyPlayingMusic = true;
            PlayIcon = new SymbolIcon(Symbol.Pause);
            MediaElement.Play();

            ProgressMaximumDisplay = ConvertToMinuteFormat(MediaElement.NaturalDuration.TimeSpan.TotalSeconds);
            ProgressMaximum = MediaElement.NaturalDuration.TimeSpan.TotalSeconds;

            IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(200);
                    progress.Report(null);
                }
            });
        }
开发者ID:dreanor,项目名称:AlbedoMusic,代码行数:19,代码来源:ViewModel.cs

示例13: Main

        static void Main(string[] args)
        {
            //Get credentials
            Console.Write("Enter your username:");
            var user = Console.ReadLine();
            Console.WriteLine();
            Console.Write("Enter your password:");
            var password = Console.ReadLine();
            Console.WriteLine();

            //Set up the service
            var service = new SpreadsheetsService("my-service");
            service.setUserCredentials(user, password);
            ListFeed listFeed = null;
            SpreadsheetFeed feed = null;
            IProgress<string> p = new Progress<string>(Console.WriteLine);

            //Get list of spreadsheets
            var getSheets = Task.Run(() =>
                {
                    p.Report("Getting all your Google spreadsheets...");
                    var query = new SpreadsheetQuery();
                    feed = service.Query(query);
                });

            getSheets.Wait();

            //Show list of spreadsheets...
            foreach (SpreadsheetEntry entry in feed.Entries.OrderBy(x => x.Title.Text))
            {
                Console.WriteLine(entry.Title.Text);
            }

            Console.WriteLine("Which spreadsheet would you like to see the contents of?");
            var title = Console.ReadLine();

            //Get list of spreadsheets
            var getInfo = Task.Run(() =>
            {
                p.Report("Reading rows from spreadsheet");
                var query = new SpreadsheetQuery();
                query.Title = title;
                feed = service.Query(query);

                var spreadsheet = feed.Entries.FirstOrDefault() as SpreadsheetEntry;
                var wsFeed = spreadsheet.Worksheets;
                var worksheet = wsFeed.Entries.FirstOrDefault() as WorksheetEntry;

                //Define the URL to request the list feed of the worksheet
                var listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
                p.Report(string.Format("Spreadsheet table link: {0}", listFeedLink.HRef));

                //Rows in spreadsheet
                var listQuery = new ListQuery(listFeedLink.HRef.ToString());
                listFeed = service.Query(listQuery);

            });

            getInfo.Wait();

            //Iterate through the rows...
            foreach (ListEntry row in listFeed.Entries)
            {
                foreach (ListEntry.Custom element in row.Elements)
                {
                    Console.WriteLine(element.Value);
                }
            }

            //NOTE: google docs always treats the first row as the header row... 
            Console.WriteLine("Type a new value for the first cell in the first column:");
            var newValue = Console.ReadLine();

            Console.WriteLine("Updating row data...");
            var updateRow = (ListEntry)listFeed.Entries[0];
            ListEntry.Custom updateMe = updateRow.Elements[0];
            updateMe.Value = newValue;
            updateRow.Update();

            Console.Read();
        }
开发者ID:thekoehl,项目名称:dot-NET-stuff-to-remember,代码行数:81,代码来源:Program.cs

示例14: Main

        static void Main(string[] args)
        {
            var localHtmlDocname = "docContents.htm";

            //Get credentials
            Console.Write("Enter your username:");
            var user = Console.ReadLine();
            Console.WriteLine();
            Console.Write("Enter your password:");
            var password = Console.ReadLine();
            Console.WriteLine();

            //Set up the service
            var service = new DocumentsService("my-service");
            service.setUserCredentials(user, password);
            DocumentsFeed listFeed = null;
            AtomFeed feed = null;
            DocumentsListQuery query = null;
            IProgress<string> p = new Progress<string>(Console.WriteLine);

            //Get list of documents
            var getList = Task.Run(() =>
            {
                p.Report("Reading list of documents");
                query = new DocumentsListQuery();
                feed = service.Query(query);
            });

            getList.Wait();

            foreach (DocumentEntry entry in feed.Entries.OrderBy(x => x.Title.Text))
            {
                if (entry.IsDocument)
                    Console.WriteLine(entry.Title.Text);
            }

            Console.WriteLine("Type the name of the document you would like to open:");
            var openDocTitle = Console.ReadLine();
            string contents = string.Empty;

            //Get list of documents
            var openDoc = Task.Run(() =>
            {
                p.Report("Reading document contents");
                query.Title = openDocTitle;
                feed = service.Query(query);

                var openMe = feed.Entries[0] as DocumentEntry;
                var stream = service.Query(new Uri(openMe.Content.Src.ToString()));
                var reader = new StreamReader(stream);
                contents = reader.ReadToEnd();

                using (var fs = File.Create(localHtmlDocname))
                {
                    using (var writer = new StreamWriter(fs))
                    {
                        contents += Environment.UserName + " was here - " + DateTime.Now.ToString() + "<br/>";
                        writer.Write(contents);
                        writer.Flush();
                        writer.Close();
                    }

                    fs.Close();
                }

                //OPTIONAL: Uncomment to save changes BACK to the google doc
                /*
                openMe.MediaSource = new MediaFileSource(localHtmlDocname, "text/html");
                var uploader = new ResumableUploader();

                //Get an authenticator
                var authenticator = new ClientLoginAuthenticator("document-access-test", ServiceNames.Documents, service.Credentials);

                //Perform the upload...
                Console.WriteLine("Saving to Google Drive...");
                uploader.Update(authenticator, openMe);
                */
            });

            openDoc.Wait();
            Console.WriteLine("Opening contents of Google doc file...");
            System.Diagnostics.Process.Start(localHtmlDocname);
        }
开发者ID:thekoehl,项目名称:dot-NET-stuff-to-remember,代码行数:83,代码来源:Program.cs

示例15: BeginUpdateImageQualityForAllSelectedImagesAsync

        /// <summary>
        /// Redo image quality calculations with current thresholds for all images selected.  Updates the database.
        /// </summary>
        private async Task BeginUpdateImageQualityForAllSelectedImagesAsync()
        {
            List<ImageRow> selectedFiles = this.database.Files.ToList();
            this.ApplyDoneButton.Content = "_Done";
            this.ApplyDoneButton.IsEnabled = false;
            this.DarkPixelRatioThumb.IsEnabled = false;
            this.DarkThreshold.IsEnabled = false;
            this.PreviousFile.IsEnabled = false;
            this.NextFile.IsEnabled = false;
            this.ScrollImages.IsEnabled = false;
            this.ResetButton.IsEnabled = false;

            IProgress<ImageQuality> updateStatus = new Progress<ImageQuality>(this.ReportProgress);
            await Task.Run(() =>
            {
                TimeSpan desiredRenderInterval = TimeSpan.FromSeconds(1.0 / Constant.ThrottleValues.DesiredMaximumImageRendersPerSecondDefault);
                DateTime mostRecentStatusDispatch = DateTime.UtcNow - desiredRenderInterval;
                object renderLock = new object();

                int fileIndex = 0;
                List<ColumnTuplesWithWhere> filesToUpdate = new List<ColumnTuplesWithWhere>();
                Parallel.ForEach(
                    new SequentialPartitioner<ImageRow>(selectedFiles),
                    Utilities.GetParallelOptions(Environment.ProcessorCount), 
                    (ImageRow file, ParallelLoopState loopState) =>
                    {
                        if (this.stop)
                        {
                            loopState.Break();
                        }

                        // if it's not a valid image, say so and go onto the next one.
                        int currentFileIndex = Interlocked.Increment(ref fileIndex);
                        ImageQuality imageQuality = new ImageQuality(file);
                        if ((imageQuality.OldImageQuality != FileSelection.Ok) && (imageQuality.OldImageQuality != FileSelection.Dark))
                        {
                            imageQuality.FileIndex = currentFileIndex;
                            imageQuality.NewImageQuality = null;
                            updateStatus.Report(imageQuality);
                            return;
                        }

                        try
                        {
                            // find the new image quality and add file to the update list
                            // See remarks in CarnassialWindow.xaml.cs about synchronous loading.
                            imageQuality.Bitmap = file.LoadBitmapAsync(this.database.FolderPath).GetAwaiter().GetResult().AsWriteable();
                            imageQuality.FileIndex = currentFileIndex;
                            imageQuality.NewImageQuality = imageQuality.Bitmap.IsDark(this.darkPixelThreshold, this.darkPixelRatio, out this.darkPixelRatioFound, out this.isColor);
                            imageQuality.IsColor = this.isColor;
                            imageQuality.DarkPixelRatioFound = this.darkPixelRatioFound;
                            if (imageQuality.OldImageQuality != imageQuality.NewImageQuality.Value)
                            {
                                filesToUpdate.Add(new ColumnTuplesWithWhere(new List<ColumnTuple> { new ColumnTuple(Constant.DatabaseColumn.ImageQuality, imageQuality.NewImageQuality.Value.ToString()) }, file.ID));
                            }
                        }
                        catch (Exception exception)
                        {
                            // file isn't there?
                            Debug.Fail("Exception while assessing image quality.", exception.ToString());
                        }

                        DateTime utcNow = DateTime.UtcNow;
                        if (utcNow - mostRecentStatusDispatch > desiredRenderInterval)
                        {
                            lock (renderLock)
                            {
                                if (utcNow - mostRecentStatusDispatch > desiredRenderInterval)
                                {
                                    mostRecentStatusDispatch = utcNow;
                                    updateStatus.Report(imageQuality);
                                }
                            }
                        }
                    });

                    this.database.UpdateFiles(filesToUpdate);
                });

            await this.DisplayImageAndDetailsAsync();
            this.ApplyDoneButton.IsEnabled = true;
            this.CancelStopButton.IsEnabled = false;
        }
开发者ID:CascadesCarnivoreProject,项目名称:Timelapse,代码行数:86,代码来源:DarkImagesThreshold.xaml.cs


注:本文中的System.Progress.Report方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。