0

我将如何在 C# 中创建线程?

在java中,我要么实现Runnable接口

class MyThread implements Runnable{
public void run(){
//metthod
}

进而

MyThread mt = new MyThread;
Thread tt = new Thread(mt);
tt.start()

或者我可以简单地扩展 Thread 类

class MyThread extends Thread{
public void run(){
//method body
}

进而

MyThread mt = new MyThread
mt.start();
4

1 回答 1

6

不,与 Java 相反,在 .NET 中您不能扩展Thread类,因为它是密封的。

因此,要在新线程中执行函数,最天真的方法是手动生成一个新线程并将要执行的函数传递给它(在这种情况下作为匿名函数):

Thread thread = new Thread(() => 
{
    // put the code here that you want to be executed in a new thread
});
thread.Start();

或者如果您不想使用匿名委托,请定义一个方法:

public void SomeMethod()
{
    // put the code here that you want to be executed in a new thread
}

然后在同一个类中启动一个新线程,传递对该方法的引用:

Thread thread = new Thread(SomeMethod);
thread.Start();

如果你想将参数传递给方法:

public void SomeMethod(object someParameter)
{
    // put the code here that you want to be executed in a new thread
}

进而:

Thread thread = new Thread(SomeMethod);
thread.Start("this is some value");

这是在后台线程中执行任务的本机方式。为了避免支付创建新线程的高昂代价,您可以使用ThreadPool中的线程之一:

ThreadPool.QueueUserWorkItem(() =>
{
    // put the code here that you want to be executed in a new thread
});

或使用异步委托执行

Action someMethod = () =>
{
    // put the code here that you want to be executed in a new thread
};
someMethod.BeginInvoke(ar => 
{
    ((Action)ar.AsyncState).EndInvoke(ar);
}, someMethod);

执行此类任务的另一种更现代的方法是使用 TPL(从 .NET 4.0 开始):

Task.Factory.StartNew(() => 
{
    // put the code here that you want to be executed in a new thread
});

所以,是的,正如你所看到的,有无数种技术可以用来在单独的线程上运行一堆代码。

于 2012-12-26T13:53:01.410 回答