C# 在读取设置时保存设置
我有一种将设置保存到文件的方法。如果 dateTimePicker 的值发生更改,则调用此方法。但我在 Form_Load 加载设置 ->我从文件中读取值并将其分配给 dateTimePicker,但是此调用方法 save_settings (原因值已更改)。此时出现问题,因为文件是由程序打开的 ->读取值和程序想要写入文件更改... 我怎样才能做到这一点?
I have a method which save settings to file. This method is called if value of dateTimePicker changed. But I have in Form_Load loading settings -> I read value from file and assign it with dateTimePicker, but this call method save_settings (couse value changed). And in this moment is problem couse the file is open by program -> reading values and program wanna write to file changes...
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你有关键部分。有很多方法可以解决这个问题。一种方法是在文件保存周围放置 Lock 语句。这样,一个线程应该在另一个线程完成后等待。但根据理解你的问题,我认为问题出在你的设计上。据我了解,您试图同时阅读和写作。也许你应该声明全局 bool 变量 isToSave 。这将指示您何时可以保存。使用文件时不要忘记使用 using 语句来释放文件
处理。
I think that you have critical section. There are plenty ways to deal with this issue . One way is to put Lock statement around file saving . This way one thread should wait after another thread is finished. But from understanding your question I think that problem is with your desing . As I understand you trying to read and write simultaneously . Maybe you should declare global bool variable isToSave . That will indicate when you can save . When working with file do not forget to use using statement to release file
Handle.
使用某种标志 - 在开始读取配置时设置它并在
finally
块中取消设置。设置该标志后,忽略对ValueChanged
的调用。由于您正在OnLoad
中加载配置,因此 dateTimePicker 的值发生变化不会有其他原因,因为您处于主 UI 线程中并且消息泵目前未泵送。Use some kind of flag - set it when you start reading your config and unset it in
finally
block. When the flag is set, ignore calls toValueChanged
. Since you are loading config inOnLoad
, there will be no other reasons for dateTimePicker's value change because you're in main UI thread and message pump is not pumping at the moment.