gpt4 book ai didi

c# - C# 如何判断线程是否结束?

转载 作者:行者123 更新时间:2023-12-02 21:41:54 31 4
gpt4 key购买 nike

我正在使用 C# 中的线程。下面是我正在使用的代码

// worker thread
Thread m_WorkerThread;

// events used to stop worker thread
ManualResetEvent m_EventStopThread;
ManualResetEvent m_EventThreadStopped;


private void btnSend_Click(object sender, EventArgs e)
{
if (btnSend.Text == "Cancel")
{
StopThread();
btnSend.Text = "Send";
return;
}
else
{
// initialize events
m_EventStopThread = new ManualResetEvent(false);
m_EventThreadStopped = new ManualResetEvent(false);

btnSend.Text = "Cancel";
// reset events
m_EventStopThread.Reset();
m_EventThreadStopped.Reset();

// create worker thread instance
m_WorkerThread = new Thread(new ThreadStart(this.ThreadFunction));

m_WorkerThread.Name = "Thread Sample"; // looks nice in Output window

m_WorkerThread.Start();
}
}
private void StopThread()
{
if (m_WorkerThread != null && m_WorkerThread.IsAlive) // thread is active
{
// set event "Stop"
m_EventStopThread.Set();
// wait when thread will stop or finish
try
{
Thread.Sleep(1000);
m_WorkerThread.Abort();
m_WorkerThread.Suspend();
}
catch { }

}
ThreadFinished(); // set initial state of buttons
return;
}
private void ThreadFunction()
{
// Doing My Work
}
private void ThreadFinished()
{
btnSend.Text = "Send";
}

上面的代码工作正常,但我有一些问题。

  1. 当线程结束时,btnSend.Text = "Send" 不会设置。
  2. 当我按取消时,线程没有正确结束。
  3. 当我按“取消”并关闭应用程序时,该应用程序将继续在后台运行。

如何解决这些问题?

最佳答案

这是如何使用 BackgroundWorker 的示例取消:

public partial class Form1 : Form
{
bool _isWorking = false;

public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
backgroundWorker1.WorkerSupportsCancellation = true;
}

private void button1_Click(object sender, EventArgs e)
{
if (_isWorking)
{
// Cancel the worker
backgroundWorker1.CancelAsync();

button1.Enabled = false;
return;
}
_isWorking = true;
button1.Text = "Cancel";
backgroundWorker1.RunWorkerAsync();
}

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 10; i++)
{
if (backgroundWorker1.CancellationPending) { return; }
Thread.Sleep(1000);
}
e.Result = "SomeResult";
}

void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_isWorking = false;
button1.Enabled = true;
button1.Text = "Run";
if (e.Cancelled) return;

// Some type checking
string theResult = e.Result as string;
if (theResult == null) return; // Or throw an error or whatever u want

MessageBox.Show(theResult);
}
}

关于c# - C# 如何判断线程是否结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303400/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com