Hello @Markus Freitag !
In C#, you can call an asynchronous function from a synchronous function by using the Result property or the Wait method of the Task object. However, it's important to note that blocking the synchronous function to wait for the asynchronous operation to complete can lead to potential deadlocks in certain scenarios, such as UI applications.
Here's an example of how you can call an asynchronous function from a synchronous function using the Result property:
csharp
void Method()
{
var task = MethodAsync();
var result = task.Result;
}
public async Task<int> MethodAsync()
{
// Asynchronous operation
await Task.Delay(1000);
return 1;
}
In the above example, the Method function is synchronous, and it calls the MethodAsync function, which is asynchronous. By accessing the Result property of the Task object returned by MethodAsync, we can block the execution of the Method function until the asynchronous operation completes and get the result.
However, it's generally recommended to keep the asynchronous flow throughout your codebase to fully leverage the benefits of asynchronous programming and avoid potential issues like deadlocks. If possible, consider making the calling function asynchronous as well. For UI applications, it's particularly important to keep the main thread responsive by using asynchronous patterns like async/await instead of blocking calls.
In your provided code, since the btnTest_Click event handler is an asynchronous void method, you can directly use the await keyword to call the TestSecondTask method asynchronously. You don't need to block and retrieve the result using Result. The current approach you have with await TestSecondTask(...) is the correct way to call the asynchronous method in an asynchronous context.
csharp
private async void btnTest_Click(object sender, EventArgs e)
{
// ...
await TestSecondTask(m_cancelTokenSource.Token, testPanel);
// ...
}
It's important to handle exceptions properly in asynchronous code, and in your case, you're handling the OperationCanceledException to catch cancellation requests.
I hope this helps!
The answer or portions of it may have been assisted by AI Source: ChatGPT Subscription
Kindly mark the answer as Accepted and Upvote in case it helped or post your feedback to help !
Regards