我是TPL世界的新手,我写了这段代码:
var myItems = myWpfDataGrid.SelectedItems;
this.Dispatcher.BeginInvoke(new Action(() =>
{
var scheduler = new LimitedConcurrencyLevelTaskScheduler(5);
TaskFactory factory = new TaskFactory(scheduler);
foreach (MyItem item in myItems)
{
Task myTask = factory.StartNew(() =>
DoLoooongWork(item)
).ContinueWith((t) =>
{
Debug.WriteLine(t.Exception.Message);
if (t.Exception.InnerException != null)
{
Debug.WriteLine(t.Exception.InnerException.Message);
}
},
TaskContinuationOptions.OnlyOnFaulted);
}
}), null);
唯一可以访问GUI的是“var myItems = myWpfDataGrid.SelectedItems;”,而且它是只读的!函数“DoLoooongWork()”访问串口等,它是一个独立的SDK函数,不访问GUI。我知道“Dispatcher.BeginInvoke”有点多余,但我不知道我能做什么,或者我做错了什么。这段代码的唯一原因是在“DoLoooongWork()”执行时释放GUI,但GUI被冻结了!
这段代码有什么问题?
编辑
感谢@Euphoric的帮助,我发现了类似于这篇文章的问题: COM Interop hang freezes entire COM system. How to cancel COM call
DoLoooongWork
内部的具体情况,我们或许可以提供更进一步的帮助。这里有一个类似的问题,供您参考:https://dev59.com/7Oo6XIcBkEYKwwoYKRDG。是的,在这里使用`Dispatcher.BeginInvoke`是多余的。 - noseratio - open to work