gpt4 book ai didi

c# - FileSystemWatcher 触发两次,程序突然停止

转载 作者:行者123 更新时间:2023-12-03 08:08:13 25 4
gpt4 key购买 nike

这个问题不太可能帮助任何 future 的访客;它只与一个小地理区域、一个特定时刻或一个非常狭窄的情况相关,而这些情况通常不适用于互联网的全局受众。如需帮助使这个问题更广泛地适用,visit the help center .




9年前关闭。




我想使用文件系统观察程序并在文件更改但触发 onchaged 事件时在表单上显示更改的信息但它被触发两次而不是一次并且我想要显示的表单从不显示并且程序停止而不显示任何异常它都会停止调试

public void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = pathOfPatientFixedFile.Remove(pathOfPatientFixedFile.IndexOf("PatientFixedData.xml")-1);
watcher.Filter = "PatientFixedData.xml";
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.EnableRaisingEvents = true;
}

private void watcher_Changed(object sender, FileSystemEventArgs e)
{
try
{
GetPatientInfo(e.FullPath);
frmPatientInfoDisplay displayPatientInfo = new frmPatientInfoDisplay(_patientInfo);
displayPatientInfo.Show();
}
catch (Exception ex)
{
}
}

GetPatientInfo 的代码
private void GetPatientInfo(String filePath)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
using (StreamReader sr = new StreamReader(filePath, Encoding.Default))
{
String line = sr.ReadToEnd();
if (line.IndexOf("<IsPatientFixed>") > 0)
{
var value = GetTagValue(line, "<IsPatientFixed>", "</IsPatientFixed>");
if (value == "true" || value == "True")
{
if (line.IndexOf("<PatientID>") > 0)
_patientInfo[0] = GetTagValue(line, "<PatientID>", "</PatientID>");
if (line.IndexOf("<PatientName>") > 0)
_patientInfo[1] = GetTagValue(line, "<PatientName>", "</PatientName>");
if (line.IndexOf("<PatientSex>") > 0)
_patientInfo[2] = GetTagValue(line, "<PatientSex>", "</PatientSex>");
if (line.IndexOf("<PatientDateOfBirth>") > 0)
_patientInfo[3] = GetTagValue(line, "<PatientDateOfBirth>", "<PatientDateOfBirth>");
}
}
}
}
catch (Exception ex)
{
}
}

最佳答案

首先,您误用了 FileSystemWatcher 因为它是一次性组件——它应该存储在一个字段中,而不是一个局部变量中,并在不再需要时丢弃。

因为您没有存储长期存在的引用,所以它可能正在被垃圾收集,这可能会导致调试停止。

此外,它可能会触发多次,具体取决于与文件交互的任何其他程序对文件执行的操作 - 并且不能保证在您收到通知时您的程序可以访问该文件。

正如评论中所提到的,您确实需要 a) 实现您的 TODO,或 b) 删除这些空的 catch block (更好的选择,IMO)。你说“没有抛出异常”,但你现在很难检测到。让程序因一个丑陋的错误而崩溃会好得多。

关于c# - FileSystemWatcher 触发两次,程序突然停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12104363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com