Leslie Jones
Leslie Jones

Reputation: 570

Call another thread function then return value

I have two thread im trying to call a function on my main thread which works fine. As seen below.

  this.Invoke(new Action(() => myFunction()));

But when i try to return a value to a variable. I cant figure out how to get the return value of this function.

This doesn't work but is what i want to achieve. The value variable should have the return value of my function in a perfect world.

   string value = this.Invoke(new Action(() => myFunction()));

Does anyone know how to achieve this?

Upvotes: 2

Views: 1296

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

The most basic way to do what you want is to use tasks. In an async function you can await the value using tasks like this:

string value = await Task.Run(myFunction);

Or, if you like, like this:

string value = await Task.Run(() => myFunction());

I prefer using Microsoft's reactive framework (Nuget "Rx-Main"), like this:

Observable.Start(myFunction).Subscribe(value =>
{
    /* do something with `value` */
});

The reactive framework has so many more operators that the TPL you can do so much more succinctly with it.

Just to give you a small flavour, here's an example query to asynchronously download a series of webpages that contain a particular string:

var query =
    from url in urls.ToObservable()
    from content in Observable.Using(
        () => new WebClient(),
        wc => Observable.Start(() => wc.DownloadString(url)))
    where content.Contains("<div class=\"foo\" />")
    select new
    {
        url,
        content,
    };

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Not exactly what you want, but capturing result of myFunction into local variable inside the delgate will get work done:

string value;
this.Invoke(new Action(() => { value= myFunction();} ));

Or as TyCobb pointed out something like following should work as Control.Invoke returns result of a function:

string value = (string)this.Invoke(myFunction);

Upvotes: 3

Related Questions