【问题标题】:Task.Factory.StartNew is not invoking the methodTask.Factory.StartNew 没有调用该方法
【发布时间】:2016-05-11 17:18:30
【问题描述】:

我是 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() 没有被解雇。这里有什么问题?

【问题讨论】:

    标签: c# multitasking


    【解决方案1】:

    您的循环条件错误导致循环内的代码无法执行,请将a &lt; Int32.MinValue更改为a &lt; Int32.MaxValue

    像这样:

    for (int a = Int32.MinValue; a < Int32.MaxValue; a++)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多