如何在我的C#应用​​程序中杀死线程?

如何在我的C#应用​​程序中杀死线程?

问题描述:

我想在Button Click事件中杀死/破坏我的应用程序中的线程.

I want to kill/destroy the thread in my application on Button Click event.

        private void stop_btn_Click(object sender, EventArgs e)
        {
            Thread.Sleep();
        }

此事件是否会挂断我的应用程序?

Does this event hang up my application?

那是我的线程开始的代码

That's the code where from my thread starts

        DataTable myTable = new DataTable();`enter code here`
        myTable = msgDataSet.Tables["text"];
        DataRow[] myRow;
        myRow = myTable.Select();

        for (int x = 0; x < myRow.Count(); x++ )
        {
            SendKeys.SendWait(myRow[x]["msg"].ToString());
            SendKeys.SendWait("{Enter}");
            int sleep = int.Parse(textBox2.Text);
            Thread.Sleep(sleep);
        }
        Thread Spam1 = new Thread(new ThreadStart(Send1));
        Spam1.Start();

请参阅此文章,以了解为什么您永远不要尝试调用Thread.Abort:

See this article for why you should never try to call Thread.Abort:

http://www.interact-sw.co. uk/iangblog/2004/11/12/cancellation

问题是您破坏了该线程中的异常安全性.这是因为Thread.Abort会在任意点在该线程内引发异常,这可能恰好在加载资源之后但在线程进入尝试支持该资源的干净卸载的try/catch之前.

The problem is that you break your exception safety within that thread. This is because Thread.Abort will throw an exception within that thread at some arbitrary point, which might be right after a resource is loaded, but before the thread enters a try/catch that would support clean unloading of that resource.

相反,您应该在该线程中运行的代码中内置协作取消功能.然后设置某种取消请求"状态,并让线程杀死自己.例如:

Instead you should build co-operative cancellation into the code you run in that thread. Then set some sort of "cancellation requested" state, and let the thread kill itself. E.g.:

foreach(var value in aBunchOfData)
{
    if(isCancelled)
    {
        break;
    }

    // Continue processing here...
}

在这种情况下,您将公开isCancelled,并将您的父线程将其设置为true.

In this case you'd expose isCancelled, and have your parent thread set it to true.

如果您使用BackgroundWorker来实现您的后台线程.

This pattern is made clear if you use a BackgroundWorker to implement your background thread.