[ACCEPTED]-In WPF, what is the equivalent of Suspend/ResumeLayout() and BackgroundWorker() from Windows Forms-backgroundworker
Best and simplest:
using(var d = Dispatcher.DisableProcessing())
{
/* your work... Use dispacher.begininvoke... */
}
Or
IDisposable d;
try
{
d = Dispatcher.DisableProcessing();
/* your work... Use dispacher.begininvoke... */
} finally {
d.Dispose();
}
0
In reading the article by Shawn Wildermuth 32 WPF Threads: Build More Responsive Apps With The Dispatcher.
I came accross the following, which states 31 you can use the Background Worker just like 30 you could in WindowsForms. Fancy that:
BackgroundWorker Now 29 that you have a sense of how the Dispatcher 28 works, you might be surprised to know that 27 you will not find use for it in most cases. In 26 Windows Forms 2.0, Microsoft introduced 25 a class for non-UI thread handling to simplify 24 the development model for user interface 23 developers. This class is called the BackgroundWorker. Figure 22 7 shows typical usage of the BackgroundWorker 21 class.
Figure 7 Using a BackgroundWorker in WPF
BackgroundWorker _backgroundWorker = new BackgroundWorker(); ... // Set up the Background Worker Events _backgroundWorker.DoWork += _backgroundWorker_DoWork; backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted; // Run the Background Worker _backgroundWorker.RunWorkerAsync(5000); ... // Worker Method void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { // Do something } // Completed Method void _backgroundWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { if (e.Cancelled) { statusText.Text = "Cancelled"; } else if (e.Error != null) { statusText.Text = "Exception Thrown"; } else { statusText.Text = "Completed"; } }
The BackgroundWorker component works 20 well with WPF because underneath the covers 19 it uses the AsyncOperationManager class, which 18 in turn uses the SynchronizationContext 17 class to deal with synchronization. In Windows 16 Forms, the AsyncOperationManager hands off 15 a WindowsFormsSynchronizationContext class 14 that derives from the SynchronizationContext 13 class. Likewise, in ASP.NET it works with 12 a different derivation of SynchronizationContext 11 called AspNetSynchronizationContext. These 10 SynchronizationContext-derived classes know 9 how to handle the cross-thread synchronization 8 of method invocation.
In WPF, this model 7 is extended with a DispatcherSynchronizationContext 6 class. By using BackgroundWorker, the Dispatcher 5 is being employed automatically to invoke 4 cross-thread method calls. The good news 3 is that since you are probably already familiar 2 with this common pattern, you can continue 1 using BackgroundWorker in your new WPF projects.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.