Task.WaitAll(tasks.ToArray());冻结[重复]

问题描述 投票:0回答:1

我会重新解释这个问题。这是我想要做的简化代码。标签将是动态的,必须在函数中传递。功能startCount()将做更多,我想要每个线程以节省时间。代码工作正常(现在计算和更改值)。 完成所有任务后,我还需要执行其他功能。 我在startCount()函数中取出了额外的任务。

至于其他例子,我没有使用await并且在startCount()删除ot任务现在程序冻结了。

private void Form1_Load(object sender, EventArgs e)
{
    strCounter.Add("66");   //Simulate reading file 
    strCounter.Add("69");

    labels = new Label[strCounter.Count];   //Create the Array of Labels

    for (int i = 0; i < strCounter.Count; i++)
    {
        labels[i] = new Label();            //Create label and add it to Form
        labels[i].Size = new Size(30, 15);
        labels[i].Location = new Point(10, 50 + (i * 20));
        labels[i].Text = strCounter[i];
        this.Controls.Add(labels[i]);
    }
}

private void button1_Click(object sender, EventArgs e)
{
    List<Task> tasks = new List<Task>();    //Create List of Tasks

    for (int i = 0; i < strCounter.Count; i++)
    {
        int ii = i;
        Task LastTask = new Task(() => startCount(i.ToString(), labels[ii]));

        tasks.Add(LastTask);
        tasks[i].ConfigureAwait(false);
        tasks[i].Start();

    }
    // This line will cause the entire program to freeze.
    // If i comment out, the program works fine.
    Task.WaitAll(tasks.ToArray());

    MessageBox.Show("Should be After");
}

private void startCount(string strCount, Label lbl)
{
    for (int i = 0; i < 100; i++)
    {
        int count = int.Parse(lbl.Text) + 1;    //Add 1
        writeLabelBox(lbl, count.ToString());   //Use Invoke function
        Thread.Sleep(20);
    }
}

public void writeLabelBox(Label l, string strA)
{
    this.Invoke((MethodInvoker)delegate()
    {
        l.Text = strA;
    });
}
c# arrays task wait
1个回答
2
投票

您已经在函数内创建了一个任务并将其返回。所以你不需要创建另一个任务。 你只是在等待错误的任务。

改变这一行:

Task LastTask = new Task(() => startCount(i.ToString(), labels[ii]));

对此:

Task LastTask = startCount(i.ToString(), labels[ii]);

并删除tasks[i].Start();,因为它已经在函数中启动了。

或保持原样,但不要在函数中创建Task

在任何情况下,为什么为每个标签创建一个任务而不只是为整个循环创建一个任务?

© www.soinside.com 2019 - 2024. All rights reserved.