在WPF中安全地訪問UI(主)線程我有一個應(yīng)用程序,每次我正在觀看的日志文件更新時都會更新我的數(shù)據(jù)網(wǎng)格(附加新文本),方法如下: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);
}當(dāng)為FileWatcher引發(fā)事件時,因?yàn)樗鼊?chuàng)建了一個單獨(dú)的線程,當(dāng)我嘗試運(yùn)行dataGridRows.Add(ds)時; 要添加新行,程序只會在調(diào)試模式下沒有任何警告的情況下崩潰。在Winforms中,這可以通過使用Invoke函數(shù)輕松解決,但我不知道如何在WPF中進(jìn)行此操作。
在WPF中安全地訪問UI(主)線程
慕桂英3389331
2019-08-27 10:23:22