开发者

How do you call a generic method on a thread?

How would I call a method with the below header on a thread?

    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))开发者_Python百科; };
        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.
    }


Why can't you just do this...

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.

    } 


I assume you may have good reasons for using a free-running Thread as opposed to the .NET thread pool, but just for reference, this is quite easy to do in C# 3.5+ with the thread pool:

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

I put the callback in there because I assume that you probably want to do something with the result; your original example (and the accepted answer) doesn't really provide any way to gain access to it.

You would invoke this method as:

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


It would be easy to make this truly generic...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜