首页 > Windows开发 > 详细

Call asynchronous method from synchronous method in C#

时间:2021-05-22 10:46:49      阅读:15      评论:0      收藏:0      [点我收藏+]
public async Task<TResult> MyMethodAsync()
{
    Task<TResult> longRunningTask = LongRunningOperationAsync();
    // independent work which doesn‘t need the result of LongRunningOperationAsync can be done here

    //and now we call await on the task 
    int result = await longRunningTask;
    
    //use the result 
    UseResult(result);

    return result;
}

public async Task<TResult> LongRunningOperationAsync() // assume we return an int from this long running operation 
{
    await Task.Delay(1000); // 1 second delay

    return result;
}

public void DoSomeWork1()
{    
    // ...
}

public void DoSomeWork2(TResult)
{    
    // ...
}

public void MyMethodSync()
{
    var task = Task.Run(async () => await MyAsyncMethod());

    DoSomeWork(); // DoSomeWork is running simultaneously with MyAsyncMethod

    var result = task.WaitAndUnwrapException(); // MyMethodSync() is blocked

    DoSomeWork2(result); // Use result
}
 

Call asynchronous method from synchronous method in C#

原文:https://www.cnblogs.com/ylron/p/14797807.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!