using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ClassLibrary
{
public class MyClass
{
public static string LongOperation()
{
Thread.Sleep(new TimeSpan(0,0,30));
return "HelloWorld";
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ClassLibrary;
namespace BackgroungWorker__HelloWorld
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
MyClass.LongOperation();
e.Result = "[Result]";
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result!=null?e.Result.ToString():" null");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void btnClose_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
else
{
this.Close();
}
}
}
}
我发现,执行以下代码后:C#BackgroundWorker的线程问题
private void btnClose_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
else
{
this.Close();//"this" means the Form object
}
}
的backgroundWorker1的线程不会立即死亡。这需要一些时间。
这是构建我的应用程序逻辑时遇到的问题。
任何人都可以在这方面帮助我吗?
实际上,这是一个数据库应用程序的模拟,其中MyClass.LogOperation() - 模拟长时间的获取操作。 – anonymous 2009-09-24 13:17:53
+1我还想要一个解决方案来取消长时间运行的异步操作(即数据库调用)。我会看... :) – Pwninstein 2009-09-24 13:40:00