I have a custom environment in which the host application starts the event loop and loads the guest application into a separate application domain. The guest application has facilities for using the event loop through the provided API. I want the guest application to be able to automatically propagate all the continuations in the event loop, as was done in the .NET GUI applications and the user interface thread. Therefore, I am creating a custom synchronization context that can do this.
But the problem is that I cannot start using this new context. Whenever I try to configure it, it reset returns to null in the next callback on the application border.
Here is a short code snippet to illustrate the problem:
using System; using System.Threading; class Test : MarshalByRefObject { public void Do() { Console.WriteLine("TID: {0}, SC: {1}", Thread.CurrentThread.ManagedThreadId, SynchronizationContext.Current != null ? "present" : "absent"); SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); } } static class Program { static void Main() { try { var domain = AppDomain.CreateDomain("Other Domain"); var obj = (Test)domain.CreateInstanceAndUnwrap(typeof(Test).Assembly.FullName, typeof(Test).FullName); obj.Do(); obj.Do(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } }
Conclusion:
TID: 1, SC: absent TID: 1, SC: absent
There is also this SynchronizationContext.SetThreadStaticContext method, which could potentially solve the above problem if it was available on the desktop.
Of course, there is always a way to explicitly set the context in each callback before doing any other work. But that seems a little lousy. In addition, I do not see an elegant way to solve this problem with a chicken egg. It works, as expected, on Mono.
source share