【发布时间】:2010-06-25 17:46:06
【问题描述】:
我在使用 C# 时遇到了一个奇怪的问题,我还无法解释。我实际上计划创建一个简单的文件查看器,它会在文件更改后自动更新显示的文本,但结果比我想象的要复杂。
我有以下基本代码:
public partial class Main : Window
{
private FileSystemWatcher watcher;
private String filePath = "C:\\";
private String fileName = "example.txt";
public Main()
{
InitializeComponent();
this.txtFile.Text = File.ReadAllText(filePath + fileName);
this.watcher = new FileSystemWatcher(filePath);
this.watcher.Changed += new FileSystemEventHandler(watcher_Changed);
this.watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite;
this.watcher.Filter = fileName;
this.watcher.EnableRaisingEvents = true;
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
String text = File.ReadAllText(e.FullPath);
this.txtFile.Text = text; // <-- here comes the exception (line 42)
}
}
现在在更改的处理程序中对 (WPF) TextField 的赋值引发了System.InvalidOperationException 异常,告诉我该对象已在不同的线程中使用。那么为什么我会得到这个异常,更重要的是,我必须做什么才能使其正常工作?
编辑
顺便说一句,无论我分配什么字符串,我都会遇到异常。
编辑2
异常的全文,但用德语:
System.InvalidOperationException wurde nicht behandelt。 Message="Der aufrufende Thread kann nicht auf dieses Objekt zugreifen, da sich das Objekt im Besitz eines anderen Threads befindet。" 来源="WindowsBase" 堆栈跟踪: 北 System.Windows.Threading.Dispatcher.VerifyAccess() bei System.Windows.DependencyObject.SetValue(DependencyProperty dp,对象值) bei System.Windows.Controls.TextBox.set_Text(字符串值) bei LiveTextViewer.Main.watcher_Changed(Object sender, FileSystemEventArgs e) in ...\Main.xaml.cs:Zeile 42。 北 System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode,UInt32 numBytes,NativeOverlapped* 重叠指针) 北 System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) 内部异常:【问题讨论】:
-
您不能从单独的线程分配 UI 对象的 Text 属性,至少不能直接分配。我会避免回答,因为我推荐的方法是 WPF 之前的方法,但我相信你会得到答案。