【发布时间】:2025-12-13 21:15:02
【问题描述】:
在一个漫长(大约 1 分钟)的过程中,我试图通过将带时间戳的消息写入文本控件来记录一些进度。但是所有消息都会同时出现。显然,所有PropertyChanged events 都在排队,直到我忙碌的过程完成,并被文本控件一次性接收。我怎样才能在忙碌的过程中“刷新”事件?我进行了搜索,但找不到用于立即处理排队事件的 Flush/Update/Dispatch 调用。
question 1194620 中有一个多线程解决方案,但我首先想尽可能避免使用多线程。在较旧的环境(C++、.Net Winforms/ASP)中,总是有像Update 这样的系统调用来中断繁忙的进程以处理未决事件。
编辑:请不要告诉我一个冗长的过程应该在另一个线程中。我同意。但这是继承的代码,在我考虑转换为多线程之前,我首先需要记录某些事件以了解它的作用。此外,这个应用程序还有许多其他问题需要先解决。另外,解决问题后,漫长的过程可能不再漫长。
我在question 18888937 中找到的解码代码中任何地方写入字符串的方法,效果很好。
这是代码隐藏。 编辑:我在接受的答案中添加了对解决方案的调用。
public partial class App : Application, INotifyPropertyChanged
{
/// <summary>
/// Property for the log message for the TextBlock control
/// </summary>
public string StartupMessage
{
get { return _StartupMessage; }
set
{
if (_StartupMessage.Length == 0)
{
_StartupMessage = string.Format("{0:HH-mm-ss} {1}",
DateTime.Now, value);
}
else
{
_StartupMessage = string.Format("{0}{1}{2:HH-mm-ss} {3}",
_StartupMessage, Environment.NewLine, DateTime.Now, value);
}
OnPropertyChanged("StartupMessage");
}
}
private string _StartupMessage = "";
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
DoEvents();//see the accepted answer below
}
}
这是文本控件:
<TextBlock x:Name="textblock_StartupMessages"
Margin="10" TextWrapping="Wrap"
Text="{Binding Path=StartupMessage, Source={x:Static Application.Current}}">
</TextBlock>
下面是我在代码中放置来自其他地方的消息的方式:
public class AllRoutesViewModel : ViewModelBase
{
public AllRoutesViewModel()
{
(System.Windows.Application.Current as App).StartupMessage =
"start of AllRoutesViewModel()";
【问题讨论】:
-
您在寻找Dispatcher.PushFrame吗?
-
你为什么不在后台线程中运行冗长的操作?
-
你不想这样做:msdn.microsoft.com/en-us/library/…,因为它很糟糕。但是,由于您似乎决心避免使用多线程方法,我认为这可能是您唯一的选择。
-
@YuvalItzchakov 你是对的,但这是继承的代码,重新设计它并非易事。无论如何,我现在处于分析阶段,需要一个日志工具。理想情况下,我会修复一些瓶颈并缩短流程,多线程不会使其更快。
-
@Roland 我并没有暗示让您的应用程序多线程会使其更快。它将做的是释放 UI 消息循环来处理传入的消息,例如您的
NotifyPropertyChanged
标签: c# wpf .net-4.0 inotifypropertychanged