I wrote a simple console application to test ConfigureAwait(false) for fixing the problem of calling an async function in a synchronized way. This is how I simulate an event and trying to call an async function in a sync way.
public static class Test2
{
private static EventHandler<int> _somethingEvent;
public static void Run()
{
_somethingEvent += OnSomething;
_somethingEvent(null, 10);
Console.WriteLine("fetch some other resources");
Console.ReadLine();
}
private static void OnSomething(object sender, int e)
{
Console.WriteLine($"passed value : {e}");
FakeAsync().Wait();
}
private static async Task FakeAsync()
{
await Task.Delay(2000).ConfigureAwait(false);
Console.WriteLine($"task completed");
}
}
the output of the code is like this:
passed value : 10
task completed
fetch some other resources
And when I change the OnSomething function to async void like this:
private static async void OnSomething(object sender, int e)
{
Console.WriteLine($"passed value : {e}");
await FakeAsync();
}
The output will change to this:
passed value : 10
fetch some other resources
task completed
You can see fetch some other resources is occurred before task completed section and this is my desired result.
My question is how can I achieve the same result by calling the async function synchronized like the first signature I wrote for the OnSomething function?
How could I use ConfigureAwait(false) to help me in this situation? Or maybe I am not using it properly.