My understanding is that if you call async code synchronously it can cause deadlock when it needs to synchronize back to the UI thread to modify UI elements or if you need to access ASP.NET HttpContext.Current
. There are workarounds to solve this problem as mentioned here:
I was looking at the "The Thread Pool Hack" approach from the first link but I need to call GetAwaiter().GetResult()
directly from the async code which is already called from a new thread e.g:
//MyWork.DoWork must execute in a separate thread due legacy code that I can't refactor right now.
public class SomeClass {
try {
var myThread = new Thread(MyWork.DoWork);
myThread.Start();
} catch (Exception ex) {
//Handle exceptions
}
}
public class MyWork {
public static bool DoWork(){
var response = MyHttpClient.MakeRequestAsync(params)
.GetAwaiter()
.GetResult();
if(!response.Succeed){
//add logs and other stuff
}
}
}
Also my call to MyHttpClient.MakeRequestAsync
is NOT using .ConfigureAwait(false);
and I can't add that since the same calls can be used in other places where it may need to synchronize back to the UI context
- Is it safe to call
.GetAwaiter().GetResult()
directly onMyHttpClient.MakeRequestAsync
since I'm already starting the work in a separate thread? - Once the
MyHttpClient.MakeRequestAsync
resumes will it resume the work in the same thread?
Update:
I cannot let the async pattern propagate I must use existing legacy code that uses the thread class so no refactoring allowed at the moment for SomeClass
.