简体   繁体   English

c#thread方法

[英]c# thread method

If I have a 如果我有

public void Method(int m)
{
  ...
}

how can I create a thread to this method? 如何为此方法创建线程?

Thread t = new Thread((Method)); 线程t =新线程((方法));

t.Start(m); t.Start(米);

is not working. 不管用。

You can do this using a lambda expression. 您可以使用lambda表达式执行此操作。 The C# compiler automatically creates the ThreadStart delegate behind the scenes. C#编译器在后台自动创建ThreadStart委托。

Thread t = new Thread(() => Method(m));
t.Start();

Note that if you change m later in your code, the changes will propagate into the thread if it hasn't entered Method yet. 请注意,如果稍后在代码中更改m ,则更改将传播到线程(如果尚未输入Method If this is a problem, you should make a copy of m . 如果这是一个问题,你应该复制m

The method you are calling requires a parameter. 您调用的方法需要一个参数。 Because it has one parameter and a return type of void you can use the following 因为它有一个参数和返回类型的void,您可以使用以下内容

ThreadPool.QueueUserWorkItem(o => Method(m));

You do not need to change the int to an object in the method signature using this method. 您无需使用此方法将int更改为方法签名中的对象。

There are advantages to using the ThreadPool over starting your own Thread manually. 使用ThreadPool比手动启动自己的Thread更有优势。 Thread vs ThreadPool 线程与ThreadPool

ThreadStart tsd = new ThreadStart(ThreadMethod);
Thread t = new Thread(tsd);
t.Start();

Thread methods needs to be a method with return type void and accepting no argument. 线程方法需要是一个返回类型为void且不接受任何参数的方法。

public void ThreadMethod() {.....}

There is another variant which is ParameterizedThreadStart 另一个变体是ParameterizedThreadStart

ParameterizedThreadStart ptsd = new ParameterizedThreadStart(ThreadParamMethod);
Thread t = new Thread(ptsd);
t.Start(yourIntegerValue);

ThreadParamMethod is a method which return type is void and accept one argument of type object. ThreadParamMethod是一个返回类型为void并接受一个object类型参数的方法。 However you can pass just about any thing as object. 但是你可以传递任何东西作为对象。

public void ThreadParamMethod(object arg) {.....}

Method needs to take an object not an int to be able to use the ParameterizedThreadStart delegate. 方法需要使用对象而不是int才能使用ParameterizedThreadStart委托。

So change m to an object and cast it to an int first off. 因此,将m更改为对象并首先将其转换为int。

please try: 请试试:

Thread t = new Thread(new ThreadStart(method)); 
t.Start();

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

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