A have a need to force certain functions of my code to run on the main thread. We are talking to a single thread black box and if I run from a worker thread my performance is unacceptable. I had been working around this for months by saving the current synchronization context and then using Post to call a function that would then execute in the main thread. I know this is meant for GUIs and I'm not sure why it had been working to date but it has now been inconsistent when we go to older versions of our base software which I must be compatible with.
I have written this basic example that shows my issue. I run a task that runs in a new thread and at a certain point I want that thread to be able to ask the main thread to perform some actions and then I want the worker thread to be able to continue along.
This is the current output:
Main (ThreadId = 1)
RunTask (ThreadId = 3)
CallBack (ThreadId = 4) << I want this to be ThreadId 1
Any help would be great and even better if it is something close to the current solution because we were days from release and I'm worried a major rewrite could cause more problems. Thanks!
public class Test
{
internal static SynchronizationContext _context;
internal static bool _busy = false;
static void Main(string[] args)
{
Console.WriteLine("Main (ThreadId = " + Thread.CurrentThread.ManagedThreadId + ")");
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
_context = SynchronizationContext.Current;
Task.Run(() => RunTask());
Console.Read();
}
public static Task RunTask()
{
Console.WriteLine("RunTask (ThreadId = " + Thread.CurrentThread.ManagedThreadId + ")");
_busy = true;
_context.Post(new SendOrPostCallback((o) =>
{
CallBack(null,
EventArgs.Empty);
}),
null);
while (_busy == true)
{
}
return null;
}
public static void CallBack(object sender, EventArgs e)
{
Console.WriteLine("CallBack (ThreadId = " + Thread.CurrentThread.ManagedThreadId + ")");
}
}