views:

148

answers:

3

If I have Thread A which is the main Application Thread and a secondary Thread. How can I check if a function is being called within Thread B?

Basically I am trying to implement the following code snippit:

public void ensureRunningOnCorrectThread()
{
    if( function is being called within ThreadB )
    {
         performIO()
    }
    else
    {
         // call performIO so that it is called (invoked?) on ThreadB
    }
}

Is there a way to perform this functionality within C# or is there a better way of looking at the problem?

EDIT 1

I have noticed the following within the MSDN documentation, although Im a dit dubious as to whether or not its a good thing to be doing! :

// if function is being called within ThreadB
if( System.Threading.Thread.CurrentThread.Equals(ThreadB) )
{

}

EDIT 2

I realise that Im looking at this problem in the wrong way (thanks to the answers below who helped me see this) all I care about is that the IO does not happen on ThreadA. This means that it could happen on ThreadB or indeed anyother Thread e.g. a BackgroundWorker. I have decided that creating a new BackgroundWorker within the else portion of the above f statement ensures that the IO is performed in a non-blocking fashion. Im not entirely sure that this is the best solution to my problem, however it appears to work!

+4  A: 

Here's one way to do it:

if (System.Threading.Thread.CurrentThread.ManagedThreadId == ThreadB.ManagedThreadId) 
            ...

I don't know enough about .NET's Thread class implementation to know if the comparison above is equivalent to Equals() or not, but in absence of this knowledge, comparing the IDs is a safe bet.

There may be a better (where better = easier, faster, etc.) way to accomplish what you're trying to do, depending on a few things like:

  • what kind of app (ASP.NET, WinForms, console, etc.) are you building?
  • why do you want to enforce I/O on only one thread?
  • what kind of I/O is this? (e.g. writes to one file? network I/O constrained to one socket? etc.)
  • what are your performance constraints relative to cost of locking, number of concurrent worker threads, etc?
  • whether the "else" clause in your code needs to be blocking, fire-and-forget, or something more sophisticated
  • how you want to deal with timeouts, deadlocks, etc.

Adding this info to your question would be helpful, although if yours is a WinForms app and you're talking about user-facing GUI I/O, you can skip the other questions since the scenario is obvious.

Keep in mind that // call performIO so that it is called (invoked?) on ThreadB implementation will vary depending on whether this is WinForms, ASP.NET, console, etc.

If WinForms, check out this CodeProject post for a cool way to handle it. Also see MSDN for how this is usually handled using InvokeRequired.

If Console or generalized server app (no GUI), you'll need to figure out how to let the main thread know that it has work waiting-- and you may want to consider an alternate implementation which has a I/O worker thread or thread pool which just sits around executing queued I/O requests that you queue to it. Or you might want to consider synchronizing your I/O requests (easier) instead of marshalling calls over to one thread (harder).

If ASP.NET, you're probably implementing this in the wrong way. It's usually more effective to use ASP.NET async pages and/or to (per above) synchronize snchronizing to your I/O using lock{} or another synchronization method.

Justin Grant
I imagine comparing just the ID is a lot more efficient then comparing the whole object! Im also looking at ways in which I can force performIO to be called on ThreadB rather than the current Thread. Any Ideas?
TK
Take a look at my updated answer above-- does that address what you're trying to do?
Justin Grant
TK, comparing the Id is _not_ more efficient than comparing 2 objects, but it is more reliable here.
Henk Holterman
+1  A: 

What you are trying to do is the opposite of what the InvokeRequired property of a windows form control does, so if it's a window form application, you could just use the property of your main form:

if (InvokeRequired) {
   // running in a separate thread
} else {
  // running in the main thread, so needs to send the task to the worker thread
}
Guffa
+1  A: 

Does your secondary thread do anything else besides the performIO() function? If not, then an easy way to do this is to use a System.Threading.ManualResetEvent. Have the secondary thread sit in a while loop waiting for the event to be set. When the event is signaled, the secondary thread can perform the I/O processing. To signal the event, have the main thread call the Set() method of the event object.

using System.Threading;
static void Main(string[] args)
{
    ManualResetEvent processEvent = new ManualResetEvent(false);
    Thread thread = new Thread(delegate() {
        while (processEvent.WaitOne()) {
            performIO();
            processEvent.Reset(); // reset for next pass...
        }
    });
    thread.Name = "I/O Processing Thread"; // name the thread
    thread.Start();

    // Do GUI stuff...

    // When time to perform the IO processing, signal the event.
    processEvent.Set();
}

Also, as an aside, get into the habit of naming any System.Threading.Thread objects as they are created. When you create the secondary thread, set the thread name via the Name property. This will help you when looking at the Threads window in Debug sessions, and it also allows you to print the thread name to the console or the Output window if the thread identity is ever in doubt.

Matt Davis