螺纹VS的ThreadStart [英] Thread vs Threadstart

查看:307
本文介绍了螺纹VS的ThreadStart的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,实际上,我还没有看到下面有什么区别:

In C#, practically, I haven't observed any difference between the following:

new Thread(SomeMethod).Start();

new Thread(new ParameterizedThreadStart(SomeMethod));

new Thread(new ThreadStart(SomeMethod));

有什么区别,如果有任何可言?

What is the difference, if there is any at all?

推荐答案

发(的ThreadStart)构造函数只能用在你的的someMethod 方法匹配的ThreadStart 委托。相反,发(ParameterizedThreadStart)要求的someMethod 匹配 ParameterizedThreadStart 委托。该签名是如下:

The Thread(ThreadStart) constructor can only be used when the signature of your SomeMethod method matches the ThreadStart delegate. Conversely, Thread(ParameterizedThreadStart) requires SomeMethod to match the ParameterizedThreadStart delegate. The signatures are below:

public delegate void ThreadStart()
public delegate void ParameterizedThreadStart(Object obj)

具体而言,这意味着你应该使用的ThreadStart 当你的方法不带任何参数,而 ParameterizedThreadStart 时,它需要一个对象参数。与前创建的线程应该调用启动开始(),而后者创建的线程应通过指定他们的说法开始(对象)

Concretely, this means that you should use ThreadStart when your method does not take any parameters, and ParameterizedThreadStart when it takes a single Object parameter. Threads created with the former should be started by calling Start(), whilst threads created with the latter should have their argument specified through Start(Object).

public static void Main(string[] args)
{
    Thread threadA = new Thread(new ThreadStart(ExecuteA));
    threadA.Start();

    Thread threadB = new Thread(new ParameterizedThreadStart(ExecuteB));
    threadB.Start("abc");

    threadA.Join();
    threadB.Join();
}

private static void ExecuteA()
{
    Console.WriteLine("Executing parameterless thread!");
}

private static void ExecuteB(Object obj)
{
    Console.WriteLine("Executing thread with parameter \"{0}\"!", obj);
}

最后,你可以调用的构造函数,而无需指定的ThreadStart ParameterizedThreadStart 委托。在这种情况下,编译器将你的方法匹配基于其签名的构造函数重载,含蓄地执行转换。

Finally, you can call the Thread constructors without specifying the ThreadStart or ParameterizedThreadStart delegate. In this case, the compiler will match your method to the constructor overload based on its signature, performing the cast implicitly.

    Thread threadA = new Thread(ExecuteA);   // implicit cast to ThreadStart
    threadA.Start();

    Thread threadB = new Thread(ExecuteB);   // implicit cast to ParameterizedThreadStart
    threadB.Start("abc");

这篇关于螺纹VS的ThreadStart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆