public void TestCallDoWorkOnBackgroundThreadAndThenCallOnSuccessOnMainThread()
 {
     var strategy = new MockBackgroundWorkerStrategy();
     var operation = new BackgroundWorker<object>(strategy);
     operation.Execute();
     strategy.CheckThatOnDoWorkWasCalled();
 }
Esempio n. 2
0
        public void TestCallDoWorkOnBackgroundThreadAndThenCallOnSuccessOnMainThread()
        {
            var strategy  = new MockBackgroundWorkerStrategy();
            var operation = new BackgroundWorker <object>(strategy);

            operation.Execute();
            strategy.CheckThatOnDoWorkWasCalled();
        }
Esempio n. 3
0
        private static void CounterHandlerAsync(object obj)
        {
            // Here we check that the provided parameter is, in fact, an IServiceProvider
            IServiceProvider provider = obj as IServiceProvider
                                        ?? throw new ArgumentException($"Passed in thread parameter was not of type {nameof(IServiceProvider)}", nameof(obj));

            // Using an infinite loop for this demonstration but it all depends on the work you want to do.
            while (true)
            {
                // Here we create a new scope for the IServiceProvider so that we can get already built objects from the Inversion Of Control Container.
                using (IServiceScope scope = provider.CreateScope())
                {
                    // Here we retrieve the singleton instance of the BackgroundWorker.
                    BackgroundWorker backgroundWorker = scope.ServiceProvider.GetRequiredService <BackgroundWorker>();

                    // And we execute it, which will log out a number to the console
                    backgroundWorker.Execute();
                }

                // This is only placed here so that the console doesn't get spammed with too many log lines
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
        }
        /// <summary>
        /// Downloads the podcast clicked.
        /// </summary>
        /// <param name='sender'>Sender.</param>
        /// <param name='e'>E.</param>
        private void downloadPodcastClicked(object sender, EventArgs e)
        {
            Episode myEpisode = EpisodeList.SelectedEpisode;
              // instantiate it within the onCreate method
              ProgressDialog downloadProgress = new ProgressDialog(this);
              downloadProgress.SetMessage(myEpisode.PodcastTitle);
              downloadProgress.Indeterminate = false;
              downloadProgress.SetTitle("Downloading Episode");
              downloadProgress.Max = 100;
              downloadProgress.SetProgressStyle(ProgressDialogStyle.Horizontal);

              long fileLength = 0;

              // create a background worker to download everything
              BackgroundWorker downloadInBackground = new BackgroundWorker(delegate(ref bool stop){
            RunOnUiThread(() => downloadProgress.Show());
            // we will read data via the response stream
            string outputPath = PortaPodderDataSource.GetEpisodeLocation(myEpisode);

            // check to see if the output path
            if(File.Exists(outputPath)) {
              return;
            }

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(myEpisode.Url.ToString());

            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            fileLength = response.ContentLength;
            downloadProgress.Max = (int)(fileLength / 1024);
            // used on each read operation
            byte[] buf = new byte[1024 * 20];

            using(System.IO.Stream resStream = response.GetResponseStream(), output = new FileStream(outputPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, buf.Length)) {
              int count = 0;
              long total = 0;

              do {
            // check for the stop condition
            if(stop){
              return;
            }

            // fill the buffer with data
            count = resStream.Read(buf, 0, buf.Length);

            // make sure we read some data
            if(count != 0) {
              total += count;
              downloadProgress.Progress = (int)(total / 1024);
              output.Write(buf, 0, count);
            }
              } while (count > 0); // any more data to read?
            }
              });
              downloadInBackground.Completed += delegate(Exception exc){
            RunOnUiThread(() => downloadProgress.Dismiss());
            string outputPath = PortaPodderDataSource.GetEpisodeLocation(myEpisode);

            // log the exception if there was one
            if(exc != null){
              PortaPodderApp.LogMessage(exc);
            }

            // delete the file if the download is incomplete or if there was an error
            if(File.Exists(outputPath) && (new FileInfo(outputPath).Length < fileLength || exc != null)){
              File.Delete(outputPath);
            }

            setGUIForDownloadState(File.Exists(outputPath));
              };

              // if the progress bar is canceled, then the stop signal needs to be given
              downloadProgress.CancelEvent += delegate(object cancelSender, EventArgs cancelEvent) {
            downloadInBackground.Stop = true;
              };
              downloadInBackground.Execute();
        }