简体   繁体   中英

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)); };
        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);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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