Manipulating a thread from another thread

In a C # program, I have 2 threads besides the main thread. When the user closes the form, I want to complete one of the threads from the main thread. How should I do it?. Please provide me the code if possible.

+2
source share
3 answers

Please do not use Thread.Abort, as recommended by other answers so far, if you do not want your program to be in an unknown state (see articles by Ian Griffiths and Chris Sells for more information). If closing the form should actually kill the application, you are probably fine, but in this case, I would recommend using a background thread in any case, which will automatically die when all the threads in the foreground are complete.

From Joe Duffy "Parallel Programming in Windows" :

There are two situations where thread interrupts are always safe:

  • The main purpose of thread interruption is to stall threads while the CLR AppDomain is unloaded. [...]
  • , , , . [...]

. [...] , , , , .

( - , .)

( ) , - (, , ). . .

+4

- . - , .

, , , .

, , ( , , C ):

int exitThread1 = false;
static void Thread1 (void) {
    while (!exitThread1) {
        // do stuff
    }
}
static void mummyProc (void) {
    int tid1 = startThread (Thread1);
    // dum de dum de dum ...
    exitThread1 = true;
    joinThread (tid1);
}
+2

, , , , . ( ) , Thread.Abort() .

:

private Thread _myWorker;

void doSomething()
{
    _myWorker = new Thread(...);
    _myWorker.Start();
}

void killWorker()
{
    _myWorker.Abort()
}

You should notice that then you call Abort()in the thread, it will throw a ThreadAbortException, which you must catch inside your working code and handle it for cleaning, etc. See Thread.Abort for details.

In addition, when your application disables its main thread (message loop, aka Application.Run), child threads will also be disabled.

+1
source

Source: https://habr.com/ru/post/1746248/


All Articles