如何在C#中完成异步任务之前等待主线程

时间:2016-09-08 00:46:28

标签: c# asynchronous

我有一个异步任务,需要比主线程更长的时间。主线程在异步任务之前完成,我没有看到Async任务的结果,例如我没有看到异步任务应该插入的DB记录。

这是我的代码

Framework 4.5

    public void Load(int id)
    {
        Task asynctask1;
        asynctask1 = CallWithAsync(id); // this is async task 
        task2(); // main thread
        task3(); // main thread

    }
    private async static Task CallWithAsync(int id)
    {
        string result = "";
        try
        {
            result = await InsertDataAsync(id);
        }
        catch (Exception ex)
        {
            //do some error logging
        }
        //return result;

    }
    static Task<string> InsertDataAsync(int id)
    {
        return Task.Run<string>(() =>
        {
            return InsertData(id);
        });
    }
    static string InsertData(int id)
    {

        try
        {

            System.Threading.Thread.Sleep(5000);//we have some code here which takes longer
            //code to insert DB record

        }
        catch (Exception ex)
        {
            //do some error logging
        }


        return "success";

    }


    public void task2()
    {
        //some thing
    }
    public void task3()
    {
        //some thing
    }

3 个答案:

答案 0 :(得分:2)

等待在方法结束时完成任务:

public void Load(int id)
{
    Task asynctask1;
    asynctask1 = CallWithAsync(id);
    task2();
    task3();
    asynctask1.Wait(); // wait for async task to complete
}

如果您将await关键字添加到async方法本身,也可以使用Load关键字。

答案 1 :(得分:0)

加载异步并等待通话?您可以使用异步void方法,但如果它是异步任务会更好,并且您在调用链的后面等待它。

public async void Load(int id)
{
  await CallWithAsync(id); // this is async task 
  task2(); // main thread
  task3(); // main thread
}

答案 2 :(得分:0)

在调用Loadasync后等待asynctask1task2()方法task3()。请注意,Load方法现在返回Task而不是void

public async Task Load(int id)
{
    Task asynctask1;
    asynctask1 = CallWithAsync(id); // this is async task 
    task2(); // main thread
    task3(); // main thread
    var result = await asynctask1;
    Console.Writeline(result); //verify returned value of asynctask1 task 
}

private async static Task<string> CallWithAsync(int id)
{
    string result = "";
    try
    {
        result = await InsertDataAsync(id);
    }
    catch (Exception ex)
    {
        //do some error logging
    }
    return result;

}
相关问题