我是C#并发新手并尝试使用两个按钮的基本应用程序,第一个按钮点击应该触发一个方法,该方法通过for循环,下一个按钮点击甚至应该取消
1 2 4 3
但是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;
}
没有被解雇。这有什么不对?
答案 0 :(得分:1)
您的循环条件错误导致循环内的代码无法执行,请将a < Int32.MinValue
更改为a < Int32.MaxValue
for (int a = Int32.MinValue; a < Int32.MaxValue; a++)