Question

I know, this may be a very easy question yet I couldn't be sure. I have this in a module:

Public theHandle As IntPtr

And this in my main form named Form1:

Private Sub Form1_HandleCreated(sender As Object, e As System.EventArgs) Handles Me.HandleCreated
    theHandle = Me.Handle
End Sub

I have many other classes, modules and threads and without using InvokeRequired, I am using this for invoking delegates from everywhere. I mean from other threads, classes, modules etc..

DirectCast(Form1.FromHandle(theHandle), Form1).Invoke(D_Calculate)

instead of:

D_Calculate.Invoke()

Is it a bad practice? Is there really a purpose of checking for InvokeRequired everytime?

Was it helpful?

Solution

You only need to check InvokeRequired where you are multi-threading and need to marshall updates back to the UI thread.

I would argue that using it everywhere is probably not a good idea because you should define and understand your threading model and therefore know exactly where the thread boundaries are and the points that need this check.

If you spinkle them liberally everywhere you are basically saying "I have no idea if this will be called only by the UI thread or not" and (assuming you actually do have multiple threads) is going to lead to a world of debugging pain when you find you've missed a point or other non-thread safe code is executed as a result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top