我有一个在运行时发布进度/状态消息的应用程序(它是一个数据库模式更新器)。由于它可以在有UI的情况下运行,也可以没有UI运行,因此这些消息必须转到控制台或简单的WPF窗口。WPF窗口以模态方式打开。它只包含一个列表框,消息将发布到该列表框中。
为了处理线程问题( GUI必须在STA线程上,而控制台不在),我使用以下逻辑:
if( args.NoUI )
{
// we're just doing plain old console-based logging
frame = new nHydrateInstallationFrame(installer) { ReportingThreshold = threshold };
frame.Execute();
}
else
{
// GUI has to be on an STA thread, so wrap ourselves and go!
frame = new nHydrateUIInstallationFrame(installer) { ReportingThreshold = threshold };
// the Execute method on an nHydrateUIInstallationFrame object calls ShowDialog().
// when the resulting window opens, the actual installation process begins to execute.
// this allows UI-based logging, and, more importantly, keeps the logging window open
// until the user explicitly closes it after the installation process completes. If
// we don't do this kind of indirect execution, the logging window will immediately close
// after the installation method ends, which will keep the user from reviewing the
// logging output
Thread staThread = new Thread(frame.Execute);
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
}这只是一个摘录,但我认为它展示了方法(即为UI创建一个单独的线程,设置它的apartmentstate,启动它并加入它)。这会导致框架(包含输出“接收器”的对象)上的Execute方法运行。Execute方法调用实际的数据库模式修改例程,并将自身作为参数传递。架构修改例程将消息写入框架,然后框架将消息输出到控制台或UI。
这都是有效的fine...except,发布到UI窗口的消息直到UI运行的进程完成后才会显示。我要补充的是,如果使用鼠标展开UI消息窗口,则例外。在这种情况下,消息在发布时会显示出来。
这让我认为我有某种焦点问题,UI窗口没有焦点,除非我玩弄它。但我不确定。我一创建UI窗口就尝试将焦点设置到该窗口,但这没有任何作用。
我会感激我的想法,我可以让消息张贴到UI窗口,以实时显示。
发布于 2011-03-27 10:15:40
我怀疑您是在UI线程上运行数据库升级程序。在这种情况下,在后台线程上运行升级例程,并从那里向窗口发送您的消息。为此,您可能需要查看BackgroundWorker类。
https://stackoverflow.com/questions/5446310
复制相似问题