Friday, February 18, 2011
BackgroundWorker Sample.
- User needs to call backgroundWorker.RunWorkerAsync(), and then in the DoWork event handler can do the work.
- The DoWork event handler is NOT called on main UI thread, ofcourse. It is called on a background thread taken from thread pool.
- We can call UI control methods/properties in ProgressChanged and RunWorkerCompleted event handlers. These handlers are called by the main UI thread.
-- sample Code ----
public SampleTwo()
{
InitializeComponent();
Thread.CurrentThread.Name = "Main";
_bg.WorkerReportsProgress = true;
_bg.WorkerSupportsCancellation = true;
_bg.DoWork += new DoWorkEventHandler(_bg_DoWork);
_bg.ProgressChanged += new ProgressChangedEventHandler(_bg_ProgressChanged);
_bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
void _bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var gotThis = Thread.CurrentThread.Name;
label1.Text = (e.ProgressPercentage.ToString() + "%");
}
// This event handler deals with the results of the background operation.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
var gotThis = Thread.CurrentThread.Name;
if (e.Cancelled == true)
{
label1.Text = "Canceled!";
}
else if (e.Error != null)
{
label1.Text = "Error: " + e.Error.Message;
}
else
{
label1.Text = "Done!";
}
}
void _bg_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
var gotThis = Thread.CurrentThread.Name;
for (int i = 1; i <= 10; i++) { if (worker.CancellationPending == true) { e.Cancel = true; break; } else { // Perform a time consuming operation and report progress. System.Threading.Thread.Sleep(500); worker.ReportProgress(i * 10); } } } private void button1_Click(object sender, EventArgs e) { _bg.RunWorkerAsync(); }
Sunday, February 13, 2011
BeginInvoke and EndInvoke Pattern.
Call a Method Asynchronously using Delegate
Now that you know how the BeginInvoke and EndInvoke methods of the Delegate class work, let us see the different ways/patterns available to use BeginInvoke() and EndInvoke() to make asynchronous calls
EndInvoke Pattern - In this pattern, we use BeginInvoke from the Main thread to call the method, then do some processing on the main thread and then call EndInvoke(). This is useful when you want to have the calling thread to continue processing at the same time the asynchronous call is executing. Here the EndInvoke() does not return until the asynchronous call has completed. In other words, the main thread waits till the asynchronous operation is complete.
WaitHandle – Using this technique, the main method calls the method asynchronously and waits for a WaitHandle before it calls EndInvoke().
Polling Pattern - In this pattern, the calling thread polls the other thread (doing async operation) periodically using the IAsyncResult object and checks whether the thread has completed. If not, it continues processing and checks the thread later. The application does not call EndInvoke() until it knows that the operation is complete. This pattern can be useful when you want your UI to be responsive, till the async operation completes.
Callback Pattern - In this pattern, the initial thread initiates the async call but does not wait or check to see if the thread that was called, has completed. This pattern can be useful if you not want to process the results of the async call in the main thread. Note: CallbackMethod would be called in the thread in which BeginInvoke is called ( a thread taken from ThreadPool).
Let us see an example of calling a method asynchronously using the EndInvoke Pattern
SafeInvoke.. will all checks and bounds.
public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous) { if (uiElement == null) { throw new ArgumentNullException("uiElement"); } if (uiElement.InvokeRequired) { if (forceSynchronous) { uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); }); } else { uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); }); } } else { if (!uiElement.IsHandleCreated) { // Do nothing if the handle isn't created already. The user's responsible // for ensuring that the handle they give us exists. return; } if (uiElement.IsDisposed) { throw new ObjectDisposedException("Control is already disposed."); } updater(); } }