Looking for a good sample of the threading in WPF
-
Wednesday, April 23, 2008 12:45 PMLooking for a good sample of the threading in WPF.
Which common way to realize the threading in WPF?
Thanks!
All Replies
-
Wednesday, April 23, 2008 12:52 PM
Threading is pretty much the same as any .NET application, except when you need to update the UI from a thread other than the UI thread, you must use the Dispatcher.Invoke/BeginInvoke methods.
I like using the Dispatcher with anonymous methods as it makes my class a little cleaner.
/* In a non-ui thread */
int x = 100;myProgressBar.Dispatcher.Invoke(System.Windows.Threading.
DispatcherPriority.Normal, (ThreadStart) delegate{
/* In the UI thread */
myProgressBar.Value = x;
});
-
Friday, April 25, 2008 4:37 AMNick Kramer and Tyler Barton has written a comprehensive article on WPF's threading model, this is the best article I've found on WPF threading:
http://blogs.msdn.com/nickkramer/attachment/553378.ashx
Hope this helps -
Friday, April 25, 2008 6:49 AM
Hello,
Here is my simple example of Threading in WPF. Hope this helps.
The Appendix C in Programming WPF is very hlepful topic about Threading in WPF.
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void btnStartThread_Click(object sender, RoutedEventArgs e)
{
System.Threading.Thread worker = new System.Threading.Thread(DoWork);
worker.IsBackground = true; // set as background thread so that it is terminated with application.
worker.Start();
}
private void DoWork()
{
ulong sum = 0;
for(int i=0; i < short.MaxValue;i++)
{
//we need to call Disptacher.Invoke to reflect UI within worker thread.
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
(Action)delegate
{ this.Title = sum.ToString(); }
);
sum += (ulong)i;
}
//Show the result of calcualtion when done.
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
(Action)delegate
{ MessageBox.Show("Sum = " + sum); }
);
}
} -
Monday, April 28, 2008 12:58 PMGracias Nyi Nyi Thann!
That's what I need! -
Monday, April 28, 2008 1:03 PMHI DmitryBoyko,
If my code is what u need, pls mark as answer.thx.
-
Monday, April 28, 2008 1:12 PM

