我是winforms编程的新手,我开始使用线程。
我已设法启动一个帖子,但现在我希望能够点击取消按钮来停止该帖子。
到目前为止,这是我的代码......
这将启动主题:
private void btnSessions_Click(object sender, EventArgs e)
{
Thread downloadThread = new Thread(new ThreadStart(DownloadThread));
downloadThread.Start();
}
这是主题:
void DownloadThread()
{
// Do the work
}
这是我想用来取消线程的按钮:
private void btnCancel_Click(object sender, EventArgs e)
{
// Stop the thread
}
任何人都可以帮我解决我需要放入btnCancel_Click的内容吗?
答案 0 :(得分:3)
您应该使用任务并行库(TPL),它支持一种取消任务的自然方式:
private CancellationTokenSource _tokenSource2;
private CancellationToken _token;
private void btnSessions_Click(object sender, EventArgs e)
{
_tokenSource2 = new CancellationTokenSource();
_token = _tokenSource2.Token;
Task task = Task.Run(() => DownloadThread(), _token);
}
private void DownloadThread()
{
while (true)
{
//do work
//cancel if needed
if (_token.IsCancellationRequested)
{
_token.ThrowIfCancellationRequested();
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
// Stop the thread
_tokenSource2.Cancel();
}
有关取消任务的详情:http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx
为什么不使用Thread.Abort
:What's wrong with using Thread.Abort()
答案 1 :(得分:2)
您需要在对象中将downloadThread设为一个字段:
Thread downloadThread;
private void btnSessions_Click(object sender, EventArgs e)
{
downloadThread = new Thread(new ThreadStart(DownloadThread));
downloadThread.Start();
}
void DownloadThread()
{
// Do the work
}
private void btnCancel_Click(object sender, EventArgs e)
{
downloadThread.Abort();
}
后台工作者将是ui相关处理的更好解决方案。
答案 2 :(得分:0)
最好不要将Thread
,特别是Thread.Abort
用于此类任务。 C#有很高的抽象包装来隐藏线程。只需使用Task
和CancellationToken
即可。
这是一个例子:
var cts = new CancellationTokenSource(); // define in class
CancellationToken ct = cts.Token;
private void btnSessions_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => DownloadThread(), ct ); // start task
}
private void DownloadThread()
{
// You need to check this at some point where cancel may occur
if (ct.IsCancellationRequested)
ct.ThrowIfCancellationRequested();
}
private void btnCancel_Click(object sender, EventArgs e)
{
cancelToken.Cancel(false); // cancel task
}
可在msdn
找到更多信息