gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:43:35 24 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/

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