Haitam Zanid Haitam Zanid - 3 months ago 12
C# Question

Return task result

I have a function called ChangeMap that runs a pathfinder and return the path (if found).
Usually I don't use it that much, but now I need to check a lot of paths, and when I run all of them, my application freeze for a moment.

It takes from 70ms to 800ms for 1 path, and so that the application doesn't freeze, I want to do the pathfinder part in a task and await the returned path.

Let's say I have this

public Path GetPath(int from, int to)
{
// Pathfinder work
return new Path(thePath);
}


I tried this but it doesn't work..

private Path GetPath2(int from, int to)
{
return Task.Run(() =>
{
return GetPath(from, to);
}).Result;
}


And if I try this, it gives me the error Cannot await Path

Path tempPath = await GetPath2(0, 10);


Anyone know how to properly do this?
How to wait for the returned value of the pathfinder and then continue, without freezing the whole application. Knowing that I have a whole bunch of functions so I can't put all the thing in a new thread :/

Answer

Try the following:

private Task<Path> GetPath2(int from, int to)
{
    return Task.Run(() =>
    {
        return GetPath(from, to);
    });
}

Then in the calling code:

Path tempPath = await GetPath2(0, 10);
Comments