Re: Multithreading and updating the GUI
- From: "Peter Duniho" <NpOeStPeAdM@xxxxxxxxxxxxxxxx>
- Date: Tue, 24 Jun 2008 13:22:04 -0700
On Tue, 24 Jun 2008 12:59:44 -0700, <b> wrote:
[...]
Now my question is if it's possible not to have the code as above in my form. Would it be possible to synchronize (or whatever) from within my worker thread.
Yes, it is possible, and without even changing the API you've designed. But IMHO it's better not to. Your form delegate method has more implicit information and can more appropriately manage the decision as to whether to call Invoke() or not. Unless your worker thread is specifically designed to deal with GUI classes (the BackgroundWorker class would be an example of this type of exception to the rule), I think it's better to leave the invoking to the actual GUI code.
For what it's worth, you could simplify your delegate method though:
public void DeviceInserted(string Address)
{
Invoke((MethodInvoker)delegate { label1.Text = "Login: " + Address; });
}
You're not specific about why you'd prefer not to have code like that which you posted, but it's possible you'd find the above preferable.
I personally dislike the MSDN-recommended technique of checking InvokeRequired. In almost every example I've ever run into, the method is used only when invoking is required. That along with my distaste for a method that is basically doing two entirely different things (invoking itself, or actually doing some work) leads me to the alternate implementation I propose above.
Even if the method is sometimes used when invoking isn't required, there's no harm in calling Invoke(). The invoked delegate will simply be called directly.
Pete
.
- Follow-Ups:
- References:
- Prev by Date: Re: ASP.NET
- Next by Date: Re: Multithreading and updating the GUI
- Previous by thread: Multithreading and updating the GUI
- Next by thread: Re: Multithreading and updating the GUI
- Index(es):
Relevant Pages
|