[英]Task.Factory.StartNew is not invoking the method
我是 C# 并发的新手,并尝试了一个带有两个按钮的基本应用程序,第一次单击按钮应该触发一个方法,该方法通过 for 循环,然后单击下一个按钮甚至应该取消
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()
没有被解雇。 这里有什么问题?
您的循环条件错误导致循环内的代码无法执行,将a < Int32.MinValue
更改a < Int32.MaxValue
像这样:
for (int a = Int32.MinValue; a < Int32.MaxValue; a++)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.