Call asynchronous method from synchronous method in C#

Posted ylron

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Call asynchronous method from synchronous method in C#相关的知识,希望对你有一定的参考价值。

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#的主要内容,如果未能解决你的问题,请参考以下文章

CUDA kernel errors might be asynchronously reported at some other API call 错误解决

Asynchronous_method_invocation 异步方法调用 让步 yielding

Asynchronous Methods for Deep Reinforcement Learning(A3C)

推荐替换已弃用的 call_user_method?

Systemd dbus sd_bus_call_method() 与数组

如何在前端显示“methods.name.call()”web3 - 方法的结果