Re: Multithreading and updating the GUI

Tech-Archive recommends: Fix windows errors by optimizing your registry



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
.



Relevant Pages

  • Re: Cartoons cause attacks, threats against EU, Denmark, Norway
    ... Recklessly refusing to invoke the Fifth Amendment, ... Someday I'll find out what I'm not invoking here. ... It's a reference to the Fifth Amendment to the United States ... Germany and the Holocaust for the Inquisition. ...
    (rec.arts.comics.strips)
  • Re: c++ delete operator parameters
    ... TypeConstructor,' why is it not allowed to deallocate by invoking ... invoke the destructor explicitly and invoke the static delete operator ... but I cannot get it to compile without some error. ... BTW, get rid of the parens; the "delete" keyword is not a function, it is ...
    (microsoft.public.vc.language)
  • Re: Advise on Real-Time update to column control
    ... I think the problem should be the multithreading ... That is in .Net Framework, when using multi-thread, ... This is the multithreading invoking rule ... invoke, then use Control.BeginInvoke method to invoke this delegate. ...
    (microsoft.public.dotnet.framework.windowsforms)
  • Re: invoking
    ... Make that "invoking a proc by space key, ... However, it won't invoke either button if focus is on X and Y, but it will invoke either button if focus is on Z". ... set class ...
    (comp.lang.tcl)