C# 对我来说是新手,我在同样的问题上苦苦挣扎了将近一周。我有这个:
private void btnWatchFile_Click(object sender, EventArgs e)
{
//code to create a watcher and allow it to reise events...
}
//watcher onCreate event
public void onCreated(object sender, FileSystemEventArgs e)
{
if (!updateNotifications )
{
stringBuilder.Remove(0, stringBuilder.Length);
stringBuilder.Append(e.FullPath);
stringBuilder.Append(" ");
stringBuilder.Append(e.ChangeType.ToString());
stringBuilder.Append(" ");
stringBuilder.Append(DateTime.Now.ToString());
updateNotifications = true;
}
}
//timer to check the flag every X time
private void timer_Tick(object sender, EventArgs e)
{
if (updateNotifications )
{
notificationListBox.Items.Insert(0, stringBuilder.ToString());
updateNotifications = false;
}
}
我什至将计时器间隔设置为 1 毫秒,但仍然缺少一些新的文件事件。我试图从onCreated 事件内部更新notificationsListBox,但我总是遇到交叉引用错误。直到我发现观察者 onCreated 事件是在主方法线程之外的线程中执行的,所以,简而言之,这是我的解决方案:
我将public delegate void Action() 作为我的类的一个属性,然后使用Invoke 从onCreated 事件内部更新notificationsListBox。下一段代码:
public void onCreated(object sender, FileSystemEventArgs e)
{
stringBuilder.Remove(0, stringBuilder.Length);
stringBuilder.Append(e.FullPath);
stringBuilder.Append(" ");
stringBuilder.Append(e.ChangeType.ToString());
stringBuilder.Append(" ");
stringBuilder.Append(DateTime.Now.ToString());
updateNotifications = true;
Invoke((Action)(() => {notificationListBox.Items.Insert(0, stringBuilder.ToString());}));
}
因此不再需要计时器及其代码。
这对我来说非常有用,我希望它适用于任何有类似情况的人。
最好的问候!!!