C#中的任务(异步/等待)循环挡住我的主线程? [英] C# (async / await) loop in task block my main thread?
本文介绍了C#中的任务(异步/等待)循环挡住我的主线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private async Task<PortalODataContext> CallConnection(Connection connection)
{
bool cancel = false;
connection.Connected = true;
var task = getConnection(connection);
while (!cancel && !task.IsCompleted)
{
Thread.Sleep(100);
if (connection.Disconected)
{
cancel = true;
}
}
return await task;
}
这是我的功能,我在主线程中调用,像这样:
That is my function that I call on the main thread Like so :
PortalODataContext portalContext = await this.CallConnection(connectionOpen);
我是新来的异步和等待,所以我只是想弄清楚为什么我的任务CallConnection挡住我的主UI线程......你们能帮助我吗?
I am new to async and await so I'm just trying to figure out why My task"CallConnection" block my main UI thread ... can you guys help me ?
喔且有的getConnection
Ohh and there is the GetConnection :
private Task<PortalODataContext> getConnection(Connection connection)
{
return Task.Factory.StartNew(() =>
{
try
{
var context = connection.ConnectToPortal();
connection.ListTemplateLib = this.ShellModel.ConnectionManager.GetTemplateLibrarys(connection);
connection.ListTemplateGrp = this.ShellModel.ConnectionManager.GetTemplateGroups(connection, connection.TemplateLibraryId);
connection.ListTemplates = this.ShellModel.ConnectionManager.GetTemplates(connection, connection.TemplateGroupId);
return context;
}
catch (Exception)
{
throw;
}
});
在此先感谢
推荐答案
Becasue的 Thread.sleep代码
异步/地等待着前两拆你的方法,而之后的await
。上半年你有一个 Thread.sleep代码
,导致调用程序线程冻结。
async/await split your method in two, before and after the await
. In the first half you have a Thread.Sleep
, causing the caller thread to freeze.
使用:
private async Task<PortalODataContext> CallConnection(Connection connection)
{
bool cancel = false;
connection.Connected = true;
var task = getConnection(connection);
while (!cancel && !task.IsCompleted)
{
await Task.Delay(100);
if (connection.Disconected)
{
cancel = true;
}
}
return await task;
}
我不完全相信你正试图在这里实现的目标。
I am not completely sure what you are trying to achieve here.
这篇关于C#中的任务(异步/等待)循环挡住我的主线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文