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#

上一篇:Win10系统gpedit.msc文件找不到如何解决?(转)


下一篇:wpf监听依赖属性变化 可实现监听窗口位置变化