为什么.Net没有Thread.Start()的通用版本? [英] Why .Net has no generic version of Thread.Start()?

查看:145
本文介绍了为什么.Net没有Thread.Start()的通用版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么.Net没有启动线程的通用方法.

I am wondering why .Net does not have a generic method for starting a thread.

例如,我们启动一个如下所示的线程....

For example we start a thread like following....

Thread th = new Thread(SayHello);
th.Start("Hello");

private static void SayHello(object obj)
        {
            string str = obj as string;
            Console.WriteLine(str);
        }

我们为什么不能说为什么.Net团队不考虑使其通用?

Why can't we have I mean why .Net team did not consider making it generic ?

类似以下内容...

Thread<string> th = new Thread<string>(SayHello);

因为当我多次将值类型传递给线程启动时,我必须进行装箱/拆箱.

Because many times when I pass value types to thread start I have to do boxing/unboxing.

推荐答案

我可以看到实现BCL的人不费心写这样的几个原因:

I can see several reasons why the people who implement BCL didn't bother writing something like this:

  1. 如果您担心性能,那么与实际创建线程相比,强制转换(即使是取消装箱)的命中率要小得多.
  2. 如果您担心类型安全,则可以轻松使用lambda:new Thread(() => SayHello("Hello")).
  3. Thread<T>将是一个令人困惑的类型,因为尚不清楚T代表什么.尤其是因为它的含义与Task<T>中的T完全不同.
  4. 如果需要,可以使用20行将Thread<T>创建为包装器(见下文).
  1. If you're worried about performance, then the cast (even if it's unboxing) will be a much smaller hit than actually creating the thread.
  2. If you're worried about type safety, you can easily use lambda: new Thread(() => SayHello("Hello")).
  3. Thread<T> would be a confusing type, because it's not clear what does that T stand for. Especially since it would have a completely different meaning than T in Task<T>.
  4. If you want, you can create your Thread<T> as a wrapper using 20 lines (see below).

因此,该问题很小,如果实际上困扰您,并且解决方案可能令人困惑,则很容易解决.这很可能是资源不花钱来实现这一点的原因.

So, the issue is tiny and easy to work around if it actually bothers you and the solution could be confusing. That's most likely why resources weren't spend implementing this.

Thread<T>的可能实现:

class Thread<T>
{
    private readonly Action<T> m_action;
    private readonly Thread m_thread;
    private T m_parameter;

    public Thread(Action<T> action)
    {
        m_action = action;
        m_thread = new Thread(DoWork);
    }

    public void Start(T parameter)
    {
        m_parameter = parameter;
        m_thread.Start();
    }

    private void DoWork()
    {
        m_action(m_parameter);
    }
}

这篇关于为什么.Net没有Thread.Start()的通用版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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