views:

1931

answers:

3

Hi! I'm creating a C# dll, which is going to be used by others developers in WinForms. For some reasons, I want to detect, if methods from this library, are called from Main (GUI) Thread and warn developer he has done such a thing (ie. in log file). Is there any reasonable way to detect calling method from main thread? Remember I have no access to WinForm application.

+8  A: 

An easy solution in this case is to declare a static control in the library assembly that is created on the Main UI thread. If you want to detect if the library is called from the main thread, then use the following

if (MyLibraryControl.InvokeRequired)
  //do your thing here
ageektrapped
This should be marked as the right answer for the question.
Rodney Foley
A: 

You could use SynchronizationContext.Current to find the current WindowsFormsSynchronizationContext, and then Post a request to it. Fetch (and remember) the managed ThreadID which the callback is invoked on, and then you can test against it later.

Pretty horrible though...

Jon Skeet
+1  A: 

The simplest option (if you have a form/control handy) is to check InvokeRequired.

In the absence if that, you could try using SynchronizationContext to simulate a Post or Send, checking what thread that happens on? Calling Send or Post will switch to the UI thread.

Marc Gravell