开发者

Multithreading/C#: Can I do a BeginInvoke on multiple UI elements?

Say I'm on a worker thread and I'd lik开发者_运维问答e to change several UI elements, a button, a textbox, etc.

Do I need to call BeginInvoke on each and every element? i.e.,

  myButton.BeginInvoke(someMethod);
  myTextBox.BeginInvoke(someOtherMethod);

Or is there a way to do one BeginInvoke and then update multiple UI elements? Thanks


No, this isn't necessary. Unless your application is running multiple message loops (highly unlikely and you'd definitely know if it was), then it doesn't matter at all which control you call BeginInvoke on; all it does is pass the delegate and arguments into a queue that gets processed as part of the message loop. Strictly speaking, there needn't be any relation between the control's interacted with and the control that you call BeginInvoke on.


Just call BeginInvoke on the form and update all the controls from there.


@James Black: My shortcut is to add a method like this:

private IAsyncResult BeginInvoke(MethodInvoker method) {
    return BeginInvoke((Delegate)method);
}

Then call it like:

BeginInvoke(() => {
    txtName.Text = name;
});


If you can use the parallel extension framework, I found this helpful:

TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

I did this in my constructor so I was on the primary thread.

Then I would call a Task so do: private void changeElements() { (new Task(() => { // do ui update })).Start(uiScheduler); }

This way you can do all the tasks you want, and it removes a lot of extra code when using BeginInvoke as you no longer need a delegate.

But, as was pointed out, you don't have to call multiple BeginInvoke calls to update the UIs, since after the first one you are already on the main thread.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜