2
我是C#併發新手,嘗試帶有兩個按鈕的基本應用程序,第一個按鈕點擊應激活一個方法,該方法經過一個for循環並且下一個按鈕單擊即使應該取消Task.Factory.StartNew未調用方法
Task t;
CancellationTokenSource tokenSource = new CancellationTokenSource();
bool cancelPressed = false;
private void button1_Click(object sender, EventArgs e)
{
var tasks = new ConcurrentBag<Task>();
var token = tokenSource.Token;
t = Task.Factory.StartNew(() => Count(token), token);
if (cancelPressed)
{
tokenSource.Cancel();
}
tasks.Add(t);
Task.WaitAll(tasks.ToArray());
}
private void Count(CancellationToken token)
{
for (int a = Int32.MinValue; a < Int32.MinValue; a++)
{
textBox1.Text = a.ToString();
if (token.IsCancellationRequested)
break;
}
}
private void button2_Click(object sender, EventArgs e)
{
cancelPressed = true;
}
但它Count()
沒有被解僱。這裏有什麼問題?