我正在尝试在我的C#代码中实现即时任务取消。我正在使用一种方法执行长时间运行的存储过程,在我的表单中,我有一个取消任务的按钮。
这里发生的事情(我想是这样),一旦sqlcommand开始执行,IsCancellationRequested不会被检查,因此任务不会被取消。
我知道我可以使用SqlCommand.Cancel,但是由于某些原因,对我来说这是不可能的。
这是我的代码,如果我在这里缺少东西,请告诉我:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private CancellationTokenSource _tokenSource = null;
private CancellationToken _token;
private Task _executionTask = null;
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd;
private void Form1_Load(object sender, EventArgs e)
{
_tokenSource = new CancellationTokenSource();
_token = _tokenSource.Token;
}
private void btnStart_Click(object sender, EventArgs e)
{
pictureBox1.Visible = true; //show progress
_executionTask = Task.Factory.StartNew(this.LongRunningTask, _token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
private void btnStop_Click(object sender, EventArgs e)
{
_tokenSource.Cancel();
pictureBox1.Visible = false; //hide progress
}
private void LongRunningTask()
{
while (true)
{
try
{
if (_token.IsCancellationRequested)
{
_token.ThrowIfCancellationRequested();
}
con.Open();
cmd = new SqlCommand("sp_SaveSendMail", con);
cmd.ExecuteNonQuery(); //once this line gets started, control never go up to check IsCancellationRequested
break;
}
catch (OperationCanceledException ex)
{
con.Close();
Console.WriteLine("Operation Cancelled");
break;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
}
}
}