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();
}
}
}
}
I found that, after executing the following code :
private void btnClose_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
else
{
this.Close();//"this" means the Form object
}
}
the backgroundWorker1's thread is not killed immediately. It takes some time.
This is been a problem in constructing my application logic.
Can anyone help me in this regard?