1

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?

Auguste Leroi
  • 215
  • 1
  • 7

1 Answers1

1

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.

ioan
  • 722
  • 4
  • 12
  • 1
    Just to be precise, when using ```PreserveThreadContext()``` you don't need to call anymore ```ConfigureAwait(false)```, it is called by default. Anyway, I personally find the naming of ```ConfigureAwait``` something obscure, which does not really tell what it does. – ioan Apr 17 '19 at 20:58
  • 1
    What does precisely mean: "in a server environment"? – Auguste Leroi Apr 18 '19 at 10:59
  • 1
    In a client app, like Windows Forms/WPF, you won't need something like ```ConfigureAwait(false)/PreserveThreadContext()```, as the task should return always in the same context (typically the UI thread). On the server, however, you don't have a UI and you truly need real multi-threading, so such constructions are pretty much a must. – ioan Apr 18 '19 at 20:28
  • 1
    To be more clear: `PreserverThreadContext()` may be configured not to call `ConfigureAwait()`. This means that, when you design a library, when calling `PreserveThreadContext()` you are on the safe side both in a server and a UI environment, provided the application behaviors are properly configured. – ioan Jul 19 '19 at 15:34