Silverlight Student
Silverlight Student

Reputation: 4118

Method runs in separate thread - how to retrieve its value in calling thread

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)?

Upvotes: 1

Views: 264

Answers (3)

Thomas Levesque
Thomas Levesque

Reputation: 292455

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
...

Upvotes: 3

goalie7960
goalie7960

Reputation: 873

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

Upvotes: 1

Jeff
Jeff

Reputation: 14279

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?

Upvotes: 0

Related Questions