【发布时间】:2022-12-19 23:29:02
【问题描述】:
在我的 WPF 应用程序中,我在 Task 下处理一些操作,如下所示:
// This gets called on a button click
public void ProcessButton()
{
ProcessTask(() =>
{
// Some code here
});
// Code below this does not executes sometime.
DoSomeOtherWork();
}
private void ProcessTask(Action action)
{
var task = Task.Factory.StartNew(action);
task.ContinueWith(r =>
{
myModal.Close(); // The modal always gets closed
// Any code here always executes
},
TaskScheduler.FromCurrentSynchronizationContext());
// Show the modal dialog which blocks the UI thread
myModal.ShowDialog();
}
对于大多数情况,DoSomeOtherWork 方法在模式关闭后执行。但是有时,它不会。没有发生错误/异常。此行为仅在生产中观察到。
这个应用程序中还有许多其他后台操作在运行,所以我不确定是否有任何干扰。该应用程序是在 .NET Framework 4.6 中构建的
【问题讨论】:
-
你总是创建一个新的 myModal 对象吗? ShowDialog 只能为一个窗口对象调用一次。
-
是的,我总是创建一个新的 myModal 然后关闭,处理它
-
TaskScheduler.FromCurrentSynchronizationContext());一个额外的)? -
可能会发生错误/异常,但您永远不会
await您的Task。您也没有检查是否完成或任何附加的异常。所以抛出的任何异常都不会显示。 -
@HSharma:当它被阻塞等待对话框关闭时,应该如何在 UI 线程上执行任务的继续......?
标签: c# .net wpf multithreading task-parallel-library