Home > Blockchain >  C# call synchronous methods from asynchronous methods
C# call synchronous methods from asynchronous methods

Time:11-22

Is there a way to call a synchronous method from with an async one?

Doing the following results in a compiler error:

DoSomething synchronously blocks. Await DoSomethingAsync instead
public async Task<int> DoStuff(bool runAsync) {
    int result;
    if (runAsync) {
        result = await DoSomethingAsync();
    } else {
        result = DoSomething();
    }
    return result;
}

Potentially related? https://github.com/microsoft/vs-threading/issues/541

What are the options here, is it possible to add a comment for the compiler to ignore?

Thanks!

CodePudding user response:

You can refer the link given below which is related to this event and also here the they call the synchronous method asynchronously.

https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously

CodePudding user response:

From looking deeper at the documentation, a comment can be added as :

#pragma warning disable VSTHRD103
...
#pragma warning restore VSTHRD103
  • Related