How to interrupt a thread running inside another function?

Monitor moni = new Monitor();
Thread t = new Thread(() => moni.CurrUsage(nics,200));
t.Start();

I start a thread named 't' inside the function Form1_Load. I have added a button. When this button is clicked, the thread 't' should stop execution and create a new thread with these parameters.

Monitor moni = new Monitor();
Thread t = new Thread(() => moni.CurrUsage(nics,950));
t.Start();

I know that in the form_load event I can use

t.Abort();
+3
source share
6 answers

Having become a tmember of the form, you can refer to it later in the button click event handler.

Graceful shutdown. Although it t.Abort()does the job, you can leave the half-finished data in the stream t. You can catch ThreadAbortExceptionin the stream tto gracefully complete processing.

. , , , , . , t.Join() t.Abort().

, .

+5

Thread t .

public partial class MainForm : Form
{
    private Thread t;
}
+2

- Thread t ( Form_Load). .

, t = new Thread(.....

, , .

+1

Thread , . varaible .

.

public class MyClass
{
  private Thread MyThread
  {
    get;
    set;
  }


  private void myfunc1()
  {
    MyThread = new Thread(() => moni.CurrUsage(nics,200)); 
    MyThread.Start();
  }

  private void myfunc2()
  {
    MyThread.Abort();

    //  I really need to wait until this thread has stopped...
    MyThread.Join();
  }

}
+1

:

, .Join() (UI) , .

, : .Abort() Monitor , , . .Join(), .

public class Monitor
{
    private bool _cancel = false;

    public void Cancel()
    {
        _cancel = true;
    }

    public void CurrUsage(Nics nics, int n)
    { 
        _cancel = false;
        // ...
        while (!_cancel)
        {
        // do some stuff
        }
    }
}

private Monitor _monitor { get; set; }
private Thread _t;
public void Button_Click(...)
{
    _monitor.Cancel()
    _t.Join()       // will return as your background thread has finished cleanly
    _t = new Thread(() => _monitor.CurrUsage(nics,950));   
    t.Start();   
}
0

, , Abort, ( .NET).

. Abort , . ( ), ( volatile bool, .

,

public class ThreadClass
{
    private volatile bool stopRequested;
    private Thread thread;

    public void Start()
    {
        stopRequested = false;
        thread = new Thread(ThreadMethod);

        thread.Start();
    }

    public void Stop()
    {
        stopRequested = true;

        if(!thread.Join(5000)) thread.Abort(); // forcefully abort if not 
                                               // completed within 5 seconds
    }

    private void ThreadMethod()
    {

    }
}

ThreadMethod. stopRequested. , ( ) . , , ( , ) , true. , , , , , .

0

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


All Articles