André Chalella
André Chalella

Reputation: 14112

What is the best way to make a thread signal another thread in .NET?

I need to have a thread signal another if the user wishes to interrupt execution, however I'm unsure about how to implement the signaling/signal-checking mechanism. I wouldn't like to have a singleton in my project (like a global bool), but is there an alternative?

In this thread people suggest proper structures for that in C++, but I don't know about anything similar in .NET. Could somebody please shed some light?

Upvotes: 10

Views: 3970

Answers (6)

Matt Howells
Matt Howells

Reputation: 41266

Try out BackgroundWorker. It supports progress updates and cancellation of a running task.

If you want one thread to wait until another thread has finished doing its thing, then Monitor.Wait and Monitor.Pulse are good, as is ManualResetEvent. However, these are not really of any use for cancelling a running task.

If you want to write your own cancellation code, you could just have a field somewhere which both threads have access to. Mark it volatile, e.g.:

private volatile bool cancelling;

Have the main thread set it to true, and have the worker thread check it periodically and set it to false when it has finished.

This is not really comparable to having a 'global variable', as you can still limit the scope of the semaphore variable to be private to a class.

Upvotes: 7

Dror Helper
Dror Helper

Reputation: 30780

It depends on what kind of synchronization you need. If you want to be able to run thread in a loop until some kind of end of execution is reached - all you need is a static bool variable. If you want one thread to wait till another thread reach a point in execution you might want to use WaitEvents (AutoResetEvent or ManualResetEvent). Iflyyou need to wait for multiple waitHandles you can use WaitHandle.WaitAll or WaitHandle.WaitAny.

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 99957

A simple solution, like a synchronized static boolean, should be all you need as opposed to a framework-based solution which copuld be overkill for your scenario. In case you still want a framework, have a look at the parallel extensions to .NET for ideas.

Upvotes: 1

torial
torial

Reputation: 13121

Look into Monitor.Wait and Monitor.Pulse. Here is an excellent article on Threading in .Net (very readable): http://www.albahari.com/threading/part4.aspx

Upvotes: 3

Statement
Statement

Reputation: 4058

A bit vague (short of time), but look into ManualResetEvent and AutoResetEvent. You also might want to look up Monitor and lock keyword.

Upvotes: 5

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

Look at the System.Runtime.Remoting namespace.

Upvotes: -2

Related Questions