在C#中创建一个线程

Ari*_*ule 0 c# multithreading

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

在java中,我将实现Runnable接口

class MyThread implements Runnable{
public void run(){
//metthod
}
Run Code Online (Sandbox Code Playgroud)

然后

MyThread mt = new MyThread;
Thread tt = new Thread(mt);
tt.start()
Run Code Online (Sandbox Code Playgroud)

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

class MyThread extends Thread{
public void run(){
//method body
}
Run Code Online (Sandbox Code Playgroud)

然后

MyThread mt = new MyThread
mt.start();
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

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

因此,要在新线程中执行函数,最天真的方法是手动生成一个新线程并将其传递给要执行的函数(在本例中为匿名函数):

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

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

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

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

Thread thread = new Thread(SomeMethod);
thread.Start();
Run Code Online (Sandbox Code Playgroud)

如果要将参数传递给方法:

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

然后:

Thread thread = new Thread(SomeMethod);
thread.Start("this is some value");
Run Code Online (Sandbox Code Playgroud)

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

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

或使用异步委托执行:

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);
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • @Joe,是的,就像我说的那样,有很多方法可以在后台线程上执行某些任务.人们已经写了关于这个主题的全书.在一个SO答案中很难涵盖所有这些.我刚刚向OP提供了一些提示,以便他可以继续他的研究,并希望下次能提出更具体的问题. (4认同)