你如何在线程上调用泛型方法?

时间:2010-03-27 03:16:11

标签: c# multithreading

如何在线程上调用带有以下标题的方法?

    public void ReadObjectAsync<T>(string filename)
    {
        // Can't use T in a delegate, moved it to a parameter.
        ThreadStart ts = delegate() { ReadObjectAcync(filename, typeof(T)); };
        Thread th = new Thread(ts);
        th.IsBackground = true;
        th.Start();
    }

    private void ReadObjectAcync(string filename, Type t)
    {
        // HOW?
    }

    public T ReadObject<T>(string filename)
    {
        // Deserializes a file to a type.
    }

3 个答案:

答案 0 :(得分:2)

为什么你不能这样做......

public void ReadObjectAsync<T>(string filename)
    {
        ThreadStart ts = delegate() { ReadObject<T>(filename); };
        Thread th = new Thread(ts);
        th.IsBackground = true;
        th.Start();
    }

    private void ReadObject<T>(string filename)
    {
        // Deserializes a file to a type.

    } 

答案 1 :(得分:2)

我认为你可能有充分的理由使用自由运行的Thread而不是.NET线程池,但仅供参考,在C#3.5+中使用线程池很容易做到:

public void ReadObjectAsync<T>(string filename, Action<T> callback)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        T result = ReadObject<T>(fileName);
        callback(result);
    });
}

我把callback放在那里因为我认为你可能想要某些结果;您的原始示例(以及接受的答案)并没有真正提供任何方式来访问它。

您可以将此方法调用为:

ReadObjectAsync<MyClass>(@"C:\MyFile.txt", c => DoSomethingWith(c));

答案 2 :(得分:1)

这很容易使这个真正的通用...

public void RunAsync<T, TResult>(Func<T, TResult> methodToRunAsync, T arg1, 
    Action<TResult> callback)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        TResult result = methodToRunAsync(arg1);
        callback(result);
    });
}