简体   繁体   English

在C#中创建线程

[英]Creating a thread in C#

How would I go about in creating a thread in C#? 我将如何在C#中创建线程?

In java I would either implement the Runnable interface 在Java中,我要么实现Runnable接口

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

and then 接着

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

or I could simply extend the Thread class 或者我可以简单地扩展Thread类

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

and then 接着

MyThread mt = new MyThread
mt.start();

No, contrary to Java, in .NET you can't extend the Thread class because it's sealed. 不,与Java相反,在.NET中,您不能扩展Thread类,因为它是密封的。

So to execute a function in a new thread the most naive way is to manually spawn a new thread and pass it the function to be executed (as anonymous function in this case): 因此,要在新线程中执行功能,最幼稚的方法是手动产生一个新线程并将要执行的功能传递给它(在本例中为匿名功能):

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

or if you don't want to use an anonymous delegate then define a method: 或者如果您不想使用匿名委托,则定义一个方法:

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

and then within the same class start a new thread passing the reference to this method: 然后在同一个类中启动一个新线程,将引用传递给此方法:

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

and if you want to pass parameters to the method: 以及是否要将参数传递给方法:

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

and then: 接着:

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

That's the native way to execute tasks in background threads. 这是在后台线程中执行任务的本机方法。 To avoid paying the high price of creating new threads you could use one of the threads from the ThreadPool : 为了避免付出高昂的代价来创建新线程,您可以使用ThreadPool中的线程之一:

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

or using an 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);

And yet another, and more modern way to execute such tasks is to use the TPL (starting from .NET 4.0): 执行此类任务的另一种更现代的方法是使用TPL(从.NET 4.0开始):

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

So, yeah, as you can see, there are like gazzilions of techniques that could be used to run a bunch of code on a separate thread. 因此,是的,正如您所看到的,有些技术可以用来在单独的线程上运行一堆代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM