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();
}
}
}
}
Je trouve que, après l'exécution du code suivant:C# BackgroundWorker Discussion Problème
private void btnClose_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
else
{
this.Close();//"this" means the Form object
}
}
fil de la backgroundWorker1 n'est pas tué immédiatement. Cela prend du temps.
Cela a été un problème dans la construction de ma logique d'application.
Quelqu'un peut-il m'aider à cet égard?
En fait, il s'agit d'une simulation d'une application DB, où MyClass.LogOperation() simule une opération d'extraction longue. – anonymous
+1 Je voudrais également une solution pour annuler les opérations asynchrones de longue durée (c'est-à-dire appel DB). Je vais regarder ... :) – Pwninstein