How to call asynchronous method from synchronous method in C#

There are different ways to call an asynchronous method from a synchronous method in C#, depending on your needs and preferences. Here are some common options:


You can use the Task.Result property of the Task object returned by the asynchronous method. This will block the calling thread until the asynchronous operation is complete and return its result. 






For example, in the C# code:


I have a public async Task<object> getProductAsync() asynchronous method that I want to call from a synchronous method. 


The asynchronous method:


public async Task<object> getProductAsync()

{

    var result = await getProductAsync();

    return result as object ;

}


However, this approach requires that you change the signature of your synchronous method to return a Task object and mark it with the async keyword. This may not be possible if you are overriding a base class method or implementing an interface that expects a synchronous method.


The synchronous method:


public object GetProduct()

{

    Task<object> task = Task.Run<object>(async () => await getProductAsync());

     return task.Result;

}


However, this approach can cause deadlocks or performance issues if the asynchronous method needs to synchronize back to its original contexts, such as the UI thread or the ASP.NET request context. To avoid this, you should use ConfigureAwait(false) on every await in the asynchronous method.


Comments

Popular posts from this blog

Build HTML and send email in D365 FO with X++

How to customize electronic reporting in D365

Batch parallelism or multithreading in Dynamics 365 for Finance and Operations

How to Enable/Disable a Form Button with X++

How to create and run the Runbase batch class in D365

Difference between InMemory and TempDB tables in D365 F&O

How to create and run the Runbase class in D365

Customize the standard excel template in D365FO

How to apply a package in LCS Dynamics 365 F&O

Conditional Statements in X++