Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 529
FuryFart Avatar asked Jan 26 '12 12:01

FuryFart


1 Answers

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);
like image 134
Rich O'Kelly Avatar answered Nov 05 '22 19:11

Rich O'Kelly