Created
May 24, 2012 19:25
-
-
Save ElvisLives/2783700 to your computer and use it in GitHub Desktop.
How to handle BackgroundWorker restarts on Errors/Exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Diagnostics; | |
using System.Threading; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace BackgroundWorkerRestart.Tests | |
{ | |
[TestClass] | |
public class BackgroundWorkerRestartTest | |
{ | |
[TestMethod] | |
public void Verify_BackgroundWorker_Behavior() | |
{ | |
// http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx | |
BackgroundWorker worker = new BackgroundWorker(); | |
worker.WorkerSupportsCancellation = true; | |
worker.WorkerReportsProgress = false; | |
worker.DoWork += new DoWorkEventHandler(Worker_DoWork); | |
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted); | |
worker.RunWorkerAsync(); | |
Thread.Sleep(1000000); | |
} | |
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) | |
{ | |
if (e.Error != null) | |
{ | |
Trace.WriteLine("Trying to restart"); | |
BackgroundWorker worker = sender as BackgroundWorker; | |
worker.RunWorkerAsync(); | |
} | |
if (e.Cancelled == true) | |
{ | |
Trace.WriteLine("I was cancelled"); | |
} | |
} | |
private void Worker_DoWork(object sender, DoWorkEventArgs e) | |
{ | |
BackgroundWorker worker = sender as BackgroundWorker; | |
int i = 0; | |
do | |
{ | |
Thread.Sleep(1000); | |
Trace.WriteLine(i); | |
i++; | |
if ((worker.CancellationPending == true)) | |
{ | |
e.Cancel = true; | |
break; | |
} | |
// if (i == 5) | |
// { | |
// worker.CancelAsync(); | |
// } | |
if (i == 10) | |
{ | |
throw new Exception("I Blew up"); | |
} | |
} while (e.Cancel == false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment