运行4语句异步并阻止UI直到所有完成

时间:2017-11-08 05:34:16

标签: c# .net asynchronous

我想执行四个语句异步,然后阻止UI,直到所有语句完成执行。

private void Test()
{
    //Run Async
    System.Threading.Thread t1 = new System.Threading.Thread(this.Task1);
    System.Threading.Thread t2 = new System.Threading.Thread(this.Task2);
    System.Threading.Thread t3 = new System.Threading.Thread(this.Task3);
    System.Threading.Thread t4 = new System.Threading.Thread(this.Task4);

    t1.Start();
    Debug.WriteLine("Task-1 started....");

    t2.Start();
    Debug.WriteLine("Task-2 started....");

    t3.Start();
    Debug.WriteLine("Task-3 started....");

    t4.Start();
    Debug.WriteLine("Task-4 started....");

    while( !v1 || !v2 || !v3 || !v4)
    {
        //Block UI
    }

    Debug.WriteLine("All task completed....!");
}

v1v2v3v4是全局布尔变量,我true Task1()时设置为Task2() 1}},...完成。

如何使用async / await实现此功能?

在我的winform应用程序中,当应用程序加载时,我有一个函数填充数据集中的所有表需要更多时间,如果它们都运行异步它可能会减少一些时间,我不希望应用程序在之前启动加载数据集。

我想要这样的东西......

private void Test()
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
    //Run Async
    System.Threading.Thread t1 = new System.Threading.Thread(this.Task1);
    System.Threading.Thread t2 = new System.Threading.Thread(this.Task2);
    System.Threading.Thread t3 = new System.Threading.Thread(this.Task3);
    System.Threading.Thread t4 = new System.Threading.Thread(this.Task4);

    t1.Start();
    Debug.WriteLine("Task-1 started....");

    t2.Start();
    Debug.WriteLine("Task-2 started....");

    t3.Start();
    Debug.WriteLine("Task-3 started....");

    t4.Start();
    Debug.WriteLine("Task-4 started....");

    while (!v1 || !v2 || !v3 || !v4)
    {
        //Block UI
    }

    Debug.WriteLine("All task completed....! " + watch.ElapsedMilliseconds.ToString());
    System.Threading.Thread.Sleep(1000);
}

我可以用async / await做同样的事吗?

1 个答案:

答案 0 :(得分:1)

您可以将Task.WhenAll用于此目的:

await Task.WhenAll(Task1, Task2, Task3, Task4);