1

I have method that return some data type

MyType MyMethod()

If I am running this method into a separate thread, how can this return type be retrieve in the calling thread (that invokes other thread executing MyMethod)?

Silverlight Student
  • 3,968
  • 10
  • 37
  • 53

3 Answers3

3

There are many ways to do it, here's one:

Func<MyType> func = MyMethod;
func.BeginInvoke(ar =>
{
    MyType result = (MyType)func.EndInvoke(ar);
    // Do something useful with result
    ...
},
null);

Here's another, using the Task API:

Task.Factory
    .StartNew(new Func<MyType>(MyMethod))
    .ContinueWith(task =>
    {
        MyType result = task.Result;
        // Do something useful with result
        ...
    });

And a last one, using the Async CTP (preview of C# 5):

MyType result = await Task.Factory.StartNew<MyType>(MyMethod);
// Do something useful with result
...
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • I'd recommend going the Task route in .Net 4. It's the newer, easier way of running concurrent processes. Like many of the "pillars" of .Net 3+, the focus is on making code more declarative, describing *what* it wants, and leaving the details of *how* to do it up to the framework. – Mel May 12 '11 at 13:45
1

I think IAsyncResult pattern is your best bet. You can find more details here.

Community
  • 1
  • 1
goalie7960
  • 863
  • 7
  • 26
0

Probably the simplest is to have both threads read from/write to the same static variable.

This thread, while slightly different, also has some ideas: How to share data between different threads In C# using AOP?

Community
  • 1
  • 1
Jeff
  • 13,943
  • 11
  • 55
  • 103