Kind of depends where you need your result. You could make use of a delegate, as the following example shows.
class Program
{
static void Main(string[] args)
{
Func<int,> theFunc = new Func<int,>(GetThreadId);
theFunc.BeginInvoke(42, TheCallback, theFunc);
Console.WriteLine("Working . . .");
Console.WriteLine("Starting thread was " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
Console.ReadKey();
}
static void TheCallback(IAsyncResult result)
{
Func<int,> theFunc = (Func<int,>)result.AsyncState;
Console.WriteLine("The thread on which the function executed was " + theFunc.EndInvoke(result));
Console.WriteLine("The thread on which this was printed was " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
Console.WriteLine("Finished . . .");
}
static string GetThreadId(int justAnInt)
{
return System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + ", just an int " + justAnInt.ToString();
}
}
Output:
Working . . .
Starting thread was 10
The thread on which the function executed was 11, just an int 42
The thread on which this was printed was 11
Finsihed . . .
As you see this method returns the result on a seperate thread as well. You could use an
ISynchronizeInvoke[
^] or something similiar to return to the calling thread though.
An alternative, as someone mentioned, could be a
BackgroundWorker[
^].
You could go hardcore with the quite heavyweight
Thread Object[
^].
Or go for the more lightweight
ThreadPool[
^].
Another option would be
Tasks[
^].
Sacha Barber actually wrote a nice series of articles on Tasks:
Task Parallel Library: 1 of n[
^].
Hope this helps.