views:

53

answers:

2

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.
    }
+1  A: 

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.

    } 
Matt Dearing
Yea I just noticed that. It appears to be working fine.
cw
Heh, you beat me to it. This looks like it should work just fine to me as well.
Dan Story
+1  A: 

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