I have this simple code:
public void Run()
{
var invokerThread = new Thread(new ThreadStart(RunOnBackground));
invokerThread.Start();
}
private void RunOnBackground()
{
Trace.WriteLine("hi");
...
}
Unfortunately when running this code (from third party process) the thread doesn't really run. Either in process explorer and in VS debugger I see that the thread is created and its state is "Running".
The main thread's apartment is STA and I've tried both STA and MTA on internal thread.
When I add to the Run()
method at the end invokerThread.Join();
then the thread does run. But then again it doesn't really help.
What am I missing?
Edit: Here is some more information regarding the code hosting -
Run()
method is called via COM interop from a process which is also managed executable assembly (the reason COM interop is used is because all other components in the system are native).
The method RunOnBackground()
includes some more code after the tracing and generally its execution lasts between 10 - 20 seconds, including starting another process and waiting for its termination. Also I have some other areas in the code where I write some debug information to the Trace. While debugging the code, Run()
runs as usual and after invokerThread.Start();
invokerThread's state is "Running" (though breakpoints inside the RunOnBackground()
method don't stop).
When I add invokerThread.Join()
at the end of the Run()
method the debugger goes to RunOnBackground()
after the Join()
.