Is there an equivalent in C# to this Java code?

c#, java, multithreading

Solution

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);

Problem

``` 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?

Original source