这是一个非常简短的问题。我完全不明白 try-catch 机制。
这是我当前的代码:
public static void WriteText(string filename, string text)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
file.Write(text);
file.Close();
}
catch(Exception exc)
{
MessageBox.Show("File is probably locked by another process.");
}
}
背景:
我正在编写与另一个应用程序共享配置文件的应用程序。
当其他应用程序使用该文件时,我需要一些带有“重试”和“中止”按钮的对话框消息框。当该消息出现时 - 我将关闭其他应用程序,然后我将尝试通过按“重试”按钮再次重写该文件。
最佳答案
我们所拥有的是使用计数器进行重试,并可能使用线程休眠。
有点像
int tries = 0;
bool completed = false;
while (!completed)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
file.Write(text);
file.Close();
completed = true;
}
catch(Exception exc)
{
tries++;
//You could possibly put a thread sleep here
if (tries == 5)
throw;
}
}
关于c# - 如何实现 "retry/abort"写入可能被其他进程使用的文件的机制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18704613/