C#中有与此Java代码等效的东西吗? [英] Is there an equivalent in C# to this Java code?

查看:62
本文介绍了C#中有与此Java代码等效的东西吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在C#代码中,我想启动一个新线程.但是我想保留将在新线程中以与启动线程相同的方法执行的代码,因为我认为这是更具可读性的代码.就像上面的Java示例一样.

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.

C#中的等效代码看起来如何?

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

正如@JonSkeet所指出的那样,如果不需要分开创建和计划,则可以使用:

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

或者在.Net 4.5+中:

Or in .Net 4.5+:

Task task = Task.Run(() =>  ... // Code to run here);

这篇关于C#中有与此Java代码等效的东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆