public class ThreadTest {
public static void main(String[] args) {
Runnable runnable = new Runnable(){
@Override
public void run(){
//Code to execute on thread.start();
}};
Thread thread = new Thread(runnable);
thread.start();
}
}
In C# Code i want to start a new thread. But i want to keep the code which will be executed in the new thread in the same method in which the thread is started because i think it is more readable code. Like in the Java example above.
How will the equivalent code in C# look like?
You can use a Task
to achieve this:
public class ThreadTest {
public static void Main(string[] args)
{
Task task = new Task(() => ... // Code to run here);
task.Start();
}
}
As @JonSkeet points out, if you do not need to separate creation and scheduling you could use:
Task task = Task.Factory.StartNew(() => ... // Code to run here);
Or in .Net 4.5+:
Task task = Task.Run(() => ... // Code to run here);
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