async-awaitkephas

What is PreserveThreadContext() when calling async functions in Kephas?


I noticed in all Kephas examples that, when invoking async methods, at the end there is a call to PreserveThreadContext(). What does this do?

Some example:

   var result = await dataContext.Query<Document>()
                                 .ToListAsync()
                                 .PreserveThreadContext();

I know about ConfigureAwait(false), is this something similar?


Solution

  • In a way, yes, meaning that in a server environment it includes also a call to ConfigureAwait(false). But it also restores the thread bound culture (and UI culture) upon returning from the async call, so that the strings can be localized in a consistent way. This is due to the fact that you may find yourself in another thread upon returning, where the culture is the default one, not the configured one. Also, you can add your own behaviors for storing/restoring other thread bound information. Check for this purpose the class https://github.com/kephas-software/kephas/blob/master/src/Kephas.Core/Application/PreserveCultureThreadContextAppLifecycleBehavior.cs, which adds the culture preservation behavior. Typically, you would implement this in an AppLifecycleBehavior, in the BeforeAppInitializeAsync method.