Q.

I read with interest all 3 of the referenced WinForms multi-threading articles.  One issue that concerned me while reading these articles was the performance of an architecture using Invoke versus synchronization locks. I wrote an application to test this performance and achieved the following results.

Synch

Run Number (Time in milliseconds)

 

 

 

Method

1

2

3

4

5

Ave

Penalty

None

312

328

312

328

312

318.4

1.00

Lock

531

500

515

500

515

512.2

1.61

Invoke

98953

101718

99796

99437

99453

99871.4

313.67

This test would seem to indicate that there is a substantial penalty involved in calling the Control.Invoke method.

Asked by Ian Silverstone. Answered by the Wonk on March 3, 2003

A.

You're absolutely right, Ian. Calling Control.Invoke has a great deal more overhead than not calling it, just as accessing shared data between threads without a lock is faster than using a lock. However, when you avoid calling Control.Invoke and access UI objects directly from the UI thread, you're writing incorrect code that could cause stability problems in your application.

The problem is that a "window" object in the underlying Windowing API in Win32, as represented by the HWND handle, has thread-affinity. It *must* be directly accessed only from the thread that created it. If it's not, the results are undefined and can cause subtle, intermittent bugs. The exact same thing could happen if you access shared data between two threads. Most of the time, it will work, but sometimes, in ways that are hard to predict or reproduce, it will fail, which is why multi-threaded code is so hard to write.

By all means skip Control.Invoke and multi-threaded synchronization locks if you've only got one thread. Further, if you need to share data between two threads that isn't related to the UI, use locks and not Control.Invoke. However, if you need to affect a UI object from a worker thread, you absolutely must use Control.Invoke to transition back to the UI thread before making that call or you're in for a world of hurt.

References

  • Safe, Simple Multithreading in Windows Forms, MSDN Online, July, 2002
  • A Second Look at Windows Forms Multithreading, MSDN Online, September, 2002
  • Safe, Simple Multithreading in Windows Forms, part 3, MSDN Online, January, 2003
  • Feedback

    I have feedback on this Ask The Wonk answer