Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting return value from Task.Run

I have the following code:

public static async Task<string> Start(IProgress<ProcessTaskAsyncExProgress> progress)
{
    const int total = 10;
    for (var i = 0; i <= total; i++)
    {
        await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));
        if (progress != null)
        {
            var args = new ProcessTaskAsyncExProgress
            {
                ProgressPercentage = (int)(i / (double)total * 100.0),
                Text = "processing " + i
            };
            progress.Report(args);
        }
    }
    return "Done";
}

private static string RunLongTask(string taskName)
{
    Task.Delay(300);
    return taskName + "Completed!";
}

How do I get back the string value of RunLongTask from this line: await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));?

I've tried:

var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture))).Result;

But I get an error saying "string is not awaitable".

like image 972
Null Reference Avatar asked Aug 05 '13 04:08

Null Reference


2 Answers

Remove the Result from the end. When you await you will get the Result back from the await-able method.

var val = await Task.Run(() => RunLongTask(i.ToString(CultureInfo.InvariantCulture)));
like image 61
Haris Hasan Avatar answered Sep 20 '22 14:09

Haris Hasan


This is not a direct answer to old question, but for others searching:

"Normally" you shouldn't do this, but sometimes you need to match a library API so you can use a wrapper function like below:

private async Task<string> WrapSomeMethod(string someParam)
{
    //adding .ConfigureAwait(false) may NOT be what you want but google it.
    return await Task.Run(() => SomeObj.SomeMethodAsync(someParam)).ConfigureAwait(false);
}

And then call that instead with .Result like below:

string blah = WrapSomeMethod(someParam).Result;
like image 21
Darren Avatar answered Sep 22 '22 14:09

Darren