在C#中创建一个线程

时间:2012-12-26 13:51:21

标签: c# multithreading

我如何在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();

1 个答案:

答案 0 :(得分: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
});

或使用asynchronous delegate execution

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

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

相关问题