开发者

Easy Threading in WPF

开发者 https://www.devze.com 2022-12-23 12:47 出处:网络
I\'ve been reading a lot about threading in C#, WPF and Silverlight but can\'t get it to work. My main problem is I have the _load (_Initialized) action and it has a lot of object creation and along

I've been reading a lot about threading in C#, WPF and Silverlight but can't get it to work.

My main problem is I have the _load (_Initialized) action and it has a lot of object creation and along with that I have timers working doing different things, this causes the startup time of the program to be very slow and obviously causes the UI to hang and it isn't a good thing for deploying to a lot of users.

My timers change values of labels and textfields but having them do that on another thread is an obvious no go.

So can someone g开发者_如何学Cive me some examples on how to achieve what I need to do?

Thanks


Push your work onto other threads, and use Dispatcher.Invoke to marshal the setting of labels and text fields back onto your UI thread.

That being said, if you can, you can also refactor your work to use the BackgroundWorker class. The progress and completion events are already marshaled back onto the UI thread, so it makes it easier to update the UI in many situations.


The trick is that your UI logic has to execute on the UI thread. There are methods provided that make this easier than it might otherwise be, but using them can be tricky. Here's how I've done it in the past:

First, you have to declare a delegate that you can feed to the Dispatcher.Invoke method:

private delegate void UIDelegate();

Then you can get your background worker setup and call it's RunWorkerAsync method:

BackgroundWorker loadWorker = new BackgroundWorker();
loadWorker.DoWork += new DoWorkEventHandler(loadWorker_DoWork);
loadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(loadWorker_RunWorkerCompleted);
loadWorker.RunWorkerAsync();

Then, to update UI elements, you have to invoke their dispatcher:

private void changeStatusLabel(string status)
{
    progressLabel.Dispatcher.Invoke(new UIDelegate(delegate
    {
        progressLabel.Content = status;
    }));
}

These are cut from larger methods and they can likely be optimized a bit. Still, that'll give you a place to start from.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号