多等待Task.Run句柄

时间:2019-10-23 15:28:51

标签: c# windows async-await

我写了2个正常函数(长任务函数),想调用异步函数。所以下面的代码在这里

Public async void AsyncTask()
        {
            Form MainForm = await Task.Run(() => CreateAppForm());
            DataTable[] MasterTables = await Task.Run(() => CreateTables());
            // How to write code for below task run complete and go to next step ?
        }

        public DataTable[] CreateTables()
        {
            // Below code is create datatable from SQL DataTable
            DataTable [] MasterTables;
            return MasterTables;
        }

        public Form CreateAppForm ()
        {
            Form masterForm= new Form();
            // write some long task code 
            return masterForm;

        }

我希望CreateTables和CreateForm同时运行(并行),并且主线程需要等待上述函数运行完毕。我能知道如何处理吗?

谢谢。

2 个答案:

答案 0 :(得分:3)

抛开这个问题是否会真正实现您想要的...

如果要启动=SUM(COUNTIFS($C$2:$C$20,"<="&O2,$J$2:$J$20,">="&O2,$J$2:$J$20,"<>"&""),COUNTIFS($C$2:$C$20,"<="&$O2,$L$2:$L$20,">="&$O2,$L$2:$L$20,"<>"&""),COUNTIFS($C$2:$C$20,"<="&$O2,$L$2:$L$20,"="&"",$J$2:$J$20,"="&"")) ,只需创建它即可。当您想要Task的结果时,您Task。因此,将await的起始行和Task的起始行分开:

await

但是,再次重申,在这种特定情况下,我不确定这是否真的是个好主意(或会做任何有意义的事情)。

答案 1 :(得分:-1)

使用Thread.WaitAll();参见Thread.WaitAll Method

var tasks = new[]
{
    Task.Factory.StartNew(() => DoSomething1()),
    Task.Factory.StartNew(() => DoSomething2()),
    Task.Factory.StartNew(() => DoSomething3())
};    
Task.WaitAll(tasks);
// Code below this line will execute after all asyncs have completed 
var x = "test";

编辑:现在存储异步方法对变量的返回;

string return1 = string.Empty;
string return2 = string.Empty;

var tasks = new[]
{
    Task.Factory.StartNew(() => return1 = "First return"),
    Task.Factory.StartNew(() => return2 = "Second return"),
};

Task.WaitAll(tasks);
Console.WriteLine(return1); // First return
Console.WriteLine(return2); // Second return