【发布时间】:2017-09-05 04:34:08
【问题描述】:
我正在使用 3 个任务同时执行 3 个任务,但是,当启动所有任务时,GUI 没有冻结,它只会变得有点慢......当它返回最后一个任务的结果时,它会完全冻结并停止更新 GUI ...
async Task UpdateBlockChain()
{
var task = Task.Factory.StartNew((Action) =>
{
while (true)
{
BlockChain blockChain = new BlockChain();
coinList[0].Price = blockChain.GetDataByNode("last");
coinList[0].Low = blockChain.GetDataByNode("low");
coinList[0].High = blockChain.GetDataByNode("high");
RefreshView();
Task.Delay(1000);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
await Task.Delay(500);
}
async Task UpdateBitFinex()
{
var task = Task.Factory.StartNew((Action) =>
{
while (true)
{
Bitfinex bitFinex = new Bitfinex();
coinList[1].Price = bitFinex.GetDataByNode("last_price");
coinList[1].Low = bitFinex.GetDataByNode("low");
coinList[1].High = bitFinex.GetDataByNode("high");
RefreshView();
Task.Delay(2000);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
await Task.Delay(500);
}
async Task UpdateBitstamp()
{
var task = Task.Factory.StartNew((Action) =>
{
while (true)
{
Bitstamp bitstamp = new Bitstamp();
coinList[2].Price = bitstamp.GetDataByNode("last");
coinList[2].Low = bitstamp.GetDataByNode("low");
coinList[2].High = bitstamp.GetDataByNode("high");
RefreshView();
Task.Delay(1000);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
await Task.Delay(500);
}
刷新视图:
void RefreshView()
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.BeginInvoke(new Action(() =>
{
dataGridView1.Update();
dataGridView1.Refresh();
}));
}
}
运行任务:
await UpdateBlockChain();
await UpdateBitFinex();
await UpdateBitstamp();
这是https://pastebin.com/DuQybhcz类的示例
我不知道我使用的方法是错误的,对于代码流错误我深表歉意。
【问题讨论】:
-
您使用的是哪个 .NET 版本?如果是 452,那么您应该使用
Task.Run(() => {})而不是Task.Factory.StartNew -
我使用 NET 4.5.1
-
永远做
await Task.Delay() -
由于您没有在无限循环中等待(正如@DennisKuypers 所说),因此您正在淹没 UI。
-
@ironstone13
however still if they would not run on UI thread - the UI would not freeze不正确。任务发送的消息比 UI 处理的要多(别忘了 UI 更新很慢。)