Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 238
André Chalella Avatar asked Sep 22 '08 16:09

André Chalella


People also ask

How do you signal between threads?

The common ways of signalling are through WaitHandle and Monitor , that can coordinate between threads by notifying (signal) them when to go ahead and when to halt. All the EventWaitHandle mentioned below are basically WaitHandle objects that can signal and wait for signals.

Can we send signal to specific thread?

A pthread_kill() call sends a signal to a specific thread. A signal that is sent to a specified thread is different from a signal that is sent to a process. When a signal is sent to a process, the signal can be handled by any thread in the process.

How do you signal a thread in Java?

The thread signaling features in Java are implemented via the wait() , notify() and notifyAll() methods that are part of the the Object class which all Java classes extend.

How are threads affected by signals?

Signals can be directed to a particular thread. If the target thread has blocked the signal from delivery, the signal remains pending on the thread until the thread unblocks the signal from delivery, or the action associated with the signal is set to ignore by any thread within the process.


1 Answers

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.

like image 185
Matt Howells Avatar answered Nov 15 '22 17:11

Matt Howells