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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With