我有一个应用程序,每当我正在监视的日志文件被更新(追加新文本)时,以以下方式更新我的数据网格:
private void DGAddRow(string name, FunctionType ft)
{
ASCIIEncoding ascii = new ASCIIEncoding();
CommDGDataSource ds = new CommDGDataSource();
int position = 0;
string[] data_split = ft.Data.Split(' ');
foreach (AttributeType at in ft.Types)
{
if (at.IsAddress)
{
ds.Source = HexString2Ascii(data_split[position]);
ds.Destination = HexString2Ascii(data_split[position+1]);
break;
}
else
{
position += at.Size;
}
}
ds.Protocol = name;
ds.Number = rowCount;
ds.Data = ft.Data;
ds.Time = ft.Time;
dataGridRows.Add(ds);
rowCount++;
}
...
private void FileSystemWatcher()
{
FileSystemWatcher watcher = new FileSystemWatcher(Environment.CurrentDirectory);
watcher.Filter = syslogPath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
if (File.Exists(syslogPath))
{
string line = GetLine(syslogPath,currentLine);
foreach (CommRuleParser crp in crpList)
{
FunctionType ft = new FunctionType();
if (crp.ParseLine(line, out ft))
{
DGAddRow(crp.Protocol, ft);
}
}
currentLine++;
}
else
MessageBox.Show(UIConstant.COMM_SYSLOG_NON_EXIST_WARNING);
}
当FileWatcher触发事件时,由于它创建了一个单独的线程,因此当我尝试运行dataGridRows.Add(ds)来添加新行时,在调试模式下程序会崩溃而没有任何警告。
在Winforms中,可以通过使用Invoke函数轻松解决此问题,但我不确定如何在WPF中处理这个问题。
Application.Current
,因为我觉得这样更清晰。 - Botz3000Dispatcher.BeginInvoke
。该方法只是将委托排队等待执行。 - Botz3000DispatcherPriority.Normal
以防止任何意外的结果。如果没有它,例如,我的程序会抛出未处理的异常,表示任务被用户取消,并且导致程序崩溃。 - B.K.