Reputation: 659
I have such code in my app:
var t = new Thread(new ThreadStart(new Action(SomeClass.SomeMethod)));
t.Start();
...
t.Join();
but as I understand, compiler does some optimization and run SomeMethod in the same thread as main code. I check this by setting different Names of the thread in t and Thread.CurrentThread. How I can create and run thread to be sure it's new thread.
Upvotes: 2
Views: 2470
Reputation: 2752
Why not use the Task library? (if you use .NET 4.0)
Task task = Task.Factory.StartNew(() =>
{
// your code here, this will be executed in a Task thread
});
Upvotes: 0
Reputation: 838216
The compiler will not optimize your code in that manner. The code will be run in a new .NET thread. There must have been an error in the way you made your observations.
Note that .NET threads aren't necessarily equivalent to OS threads:
An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.
You could in theory see two managed threads with the same Windows thread ID, but the Thread.Name
property will still be different (assuming you initally set the names to two different values).
If you could post the code you used where you observed something being run in the wrong thread it might be possible to discover what error you have made.
Upvotes: 5
Reputation: 71573
As I understand it, if you tell a program to run a task in a new thread, that's exactly what will happen. Those two threads may end up running on the same core (because your calling thread may not do much except wait for the other thread to complete), but you will have two different memory spaces and execution pointers in your process.
An easy way to prove it is to open up task manager, set a breakpoint in SomeMethod, check the thread count of VS (devenv.exe) in the Processes tab, then hit the Debug button to launch your program. When it hits the breakpoint, examine the thread count again; you'll have two new threads, one for the main program execution flow and one for your worker thread. There may be one more for the attached debugger.
Upvotes: 1
Reputation: 300559
I think you have made an error in your code. Try this:
Thread.CurrentThread.Name = "main";
var t = new Thread(new ThreadStart(new Action(SomeClass.SomeMethod)));
t.Name = "worker";
t.Start();
// ...
t.Join();
Be aware that Thread.Name is a write-once property. It is therefore a bad idea to name thread pool threads!
Upvotes: 1