3

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?

H H
  • 263,252
  • 30
  • 330
  • 514
gunakkoc
  • 1,069
  • 11
  • 30
  • 1
    Why are you caching the Handle?? It can be re-created sometimes. Simply store the Form reference. As a proper read-only property. – H H Jan 25 '13 at 09:13
  • I didn't know that. Thank you. In what cases it is re-created? – gunakkoc Jan 25 '13 at 09:18
  • Don't know the list but it could be when setting certain properties (Border, MDIxxx, ...). But HandleCrerated will fire so you're code is safe. Just unnecessarily complex. – H H Jan 25 '13 at 09:22
  • C# doesn't do DirectCast et al. I removed that tag for good reasons. – H H Jan 25 '13 at 09:23
  • The point wasn't the DirectCast. I thought anyone with deep understanding of .NET and threading can answer the question. Also anyone knowing C# can understand this type of simple VB code, I guess. – gunakkoc Jan 25 '13 at 09:33
  • The tags are about the content, not about the desired audience. – H H Jan 25 '13 at 09:46

1 Answers1

6

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.

Paolo
  • 22,188
  • 6
  • 42
  • 49