【发布时间】:2016-08-11 12:45:39
【问题描述】:
我从 UI 线程启动一个长时间运行的任务 (T1) 作为进程并等待其完成。只有当用户手动关闭时,T1 才会退出。如果用户没有关闭该任务,则 UI 线程会在 while 循环中继续等待。 10-15 小时后,主程序退出,但下面给出了例外情况。据我了解,这是因为 UI Dispatcher 正忙于process.WaitForExit(300000),所以它无法处理消息队列,并且队列在相当长的一段时间后变得满了。我想问一下如何清除UI调度程序消息队列,使其在长时间运行时不会抛出异常。
我知道在 UI 线程上启动长时间运行的任务不是一个好习惯,我们可以使用 Background Worker。
WPF 应用程序中的 UI 线程
// Stop the process from opening a new window
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
// Setup executable and parameters
process.StartInfo.FileName = "Some .exe path";
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardOutput = false;
process.StartInfo.RedirectStandardError = false;
if (false == process.Start())
{
return false;
}
while (!process.WaitForExit(300000))
{
// here I want to Process Dispather queue tasks if any present so that the queue does not become full
}`
生成的异常:
Exception Info: System.ComponentModel.Win32Exception
Stack:
at MS.Win32.UnsafeNativeMethods.PostMessage(System.Runtime.InteropServices.HandleRef, MS.Internal.Interop.WindowMessage, IntPtr, IntPtr)
at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean, System.Nullable`1)
at System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr)
at System.Windows.Interop.HwndTarget.HandleMessage(MS.Internal.Interop.WindowMessage, IntPtr, IntPtr)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
at MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
at System.Threading.SynchronizationContext.WaitHelper(IntPtr[], Boolean, Int32)
at System.Windows.Threading.DispatcherSynchronizationContext.Wait(IntPtr[], Boolean, Int32)
at System.Threading.SynchronizationContext.InvokeWaitMethodHelper(System.Threading.SynchronizationContext, IntPtr[], Boolean, Int32)
at System.Threading.WaitHandle.WaitOneNative(System.Runtime.InteropServices.SafeHandle, UInt32, Boolean, Boolean)
at System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle, Int64, Boolean, Boolean)
at System.Threading.WaitHandle.WaitOne(Int32, Boolean)
at System.Diagnostics.Process.WaitForExit(Int32)
【问题讨论】:
标签: c# wpf multithreading dispatcher postmessage