2016-08-24 294 views
0

我有一个函数叫做ChangeMap,它运行一个探路者并返回路径(如果找到的话)。 通常我不会那么用,但现在我需要检查很多路径,并且当我运行它们时,我的应用程序会冻结一会儿。返回任务结果

一条路径需要70ms到800ms,并且应用程序不冻结,我想在任务中执行探路者部分并等待返回的路径。

比方说,我有这个

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

我试过,但它不工作..

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

如果我试试这个,它给我的错误不能等待路径

Path tempPath = await GetPath2(0, 10); 

任何人都知道如何正确地做到这一点? 如何等待探路者的返回值,然后继续,而不冻结整个应用程序。知道我有一大堆的功能,所以我不能把所有的东西在一个新的线程:/

+1

'GetPath2'必须是'私人异步任务 GetPath2'。此外,还有一个约定用“Async”后缀异步方法。 – zerkms

+0

此外,值得一读:https://blogs.msdn.microsoft.com/pfxteam/2012/03/24/should-i-expose-asynchronous-wrappers-for-synchronous-methods/ – zerkms

+0

应用程序仍冻结与:/ – Haytam

回答

1

尝试以下操作:

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

然后调用代码:

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

谢谢,这不会冻结应用程序。 – Haytam