Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start in a new thread in the same method

I'm beginner in the usage of threads and in the examples that I've seen (as here and here) a new thread must be assigned to a method. But, is there a way of making that inside the method? I'm looking for something like this:

public void MyMethod()
{
//Start new thread that affects only this method

//Do stuff
//More stuff

}

Thank you.

like image 452
Sturm Avatar asked Oct 20 '22 13:10

Sturm


1 Answers

You can start anonymous method or lambda if you don't want to create separate method.

Simplest way:

Task.Run(()=>{
  // Your new thread code
});

Be aware that this creates closure and parent method variables you use in your thread will not be disposed until your thread is done. Also it's not a good practice to start a long running threads like this, because it uses thread pool.

So in this case you can do something like in the code below, or use more verbose syntax for creating tasks and specify TaskCreationOptions.LongRunning parameter.

new Thread((ThreadStart)delegate() {
 // Your new thread code
}).Start();

You can put new Thread object into variable to control it later.

like image 156
Anri Avatar answered Oct 23 '22 03:10

Anri