Przemysław Michalski
Przemysław Michalski

Reputation: 9847

Is BeginInvoke/EndInvoke good practice for invoking on main thread?

Is it good practice to invoke delegate for MainForm thread - this way?:

Txt.MainForm.EndInvoke(
Txt.MainForm.BeginInvoke(
    new MethodInvoker(delegate() 
       { // code here }
)));

Upvotes: 4

Views: 1643

Answers (3)

NOtherDev
NOtherDev

Reputation: 9672

Not considering the thing that other mentioned (I believe this EndInvoke - BeginInvoke chain is just an example usage of delegate): Using delegates is 100% OK. If this is the only usage of the delegate body, there's no need to define it as a named method. It is cleaner in the code and there's no need to jump through the file. Consider using newer syntax for delegates:

new MethodInvoker(() => { // code here })

Upvotes: 0

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

It doesn't make a lot of sense as the code fires up an asynchronous call and then immediately waits for the call to finish. I.e. you end up waiting on the calling thread.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500215

No - because if you're calling EndInvoke, that will block until the delegate has completed. If you want that behaviour, just use Invoke instead.

To put it another way: if you're trying to do something other than blocking until your (presumably UI-modifying) delegate has executed in the UI thread, you should explain what that something is. If there isn't anything else, then Invoke will give you simpler code.

Upvotes: 8

Related Questions