C# 等待资源可用吗?
当我得到以下信息时,是否有一个好方法来执行此代码(等待此文件解锁): 该进程无法访问该文件,因为另一进程正在使用该文件 我正在开发一个web应用程序,因此我可以从多个不同的应用程序同时访问此文件C# 等待资源可用吗?,c#,asp.net,C#,Asp.net,当我得到以下信息时,是否有一个好方法来执行此代码(等待此文件解锁): 该进程无法访问该文件,因为另一进程正在使用该文件 我正在开发一个web应用程序,因此我可以从多个不同的应用程序同时访问此文件 bool isLock = false; do { try { File.WriteAllText(path, value, Encoding.Unicode); isLock = false; } catch {
bool isLock = false;
do
{
try
{
File.WriteAllText(path, value, Encoding.Unicode);
isLock = false;
}
catch
{
Thread.Sleep(30);
isLock = true;
}
}while (isLock);
如果您绝对必须这样做,并且您无法控制使用该文件的应用程序,那么您的代码几乎就在那里了
它只需要稍微更坚固一些:
public static bool TryWriteText(string path, string text, TimeSpan timeout)
{
Contract.Requires(path != null); // Or replace with: if (path == null) throw new ArgumentNullException("path");
Contract.Requires(text != null); // Or replace with: if (text == null) throw new ArgumentNullException("text");
Stopwatch stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed < timeout)
{
try
{
File.WriteAllText(path, text);
return true;
}
catch (IOException){} // Ignore IOExceptions until we time out, then return false.
Thread.Sleep(100); // 100ms is rather short - it could easily be 1000 I think.
} // Perhaps this should be passed in as a parameter.
return false;
}
但是,您应该在万不得已的情况下才使用此类代码。当场景中有多个应用程序时,您的lock变量没有任何用处 而是测试是否可以File.OpenWrite,然后写入该文件。 如果无法访问文件循环并等待或写入临时文件,然后启动另一个线程循环并等待,直到临时文件可以合并 也许更好的办法是立即将其存储到temp,并让看门狗写入存储文件
public void SomeWhereInYourWebServerApplication
{
FileSystemWatcher fsw = new FileSystemWatcher("tempfolder");
fsw.Created += fsw_Created;
// save new entries to tempfolder
}
void fsw_Created(object sender, FileSystemEventArgs e)
{
foreach (string file in Directory.GetFiles("tempfolder"))
{
try
{
string fileText = File.ReadAllText(file);
File.AppendAllText("myStorage.txt", fileText);
File.Delete(file);
}
catch
{
// for me it's ok when we try to append the file the next time
// something new is coming
}
}
}
就像我想的那样简单
当涉及到文件时,不要忘记进行适当的异常处理。您不能为每个并发用户获取文件的临时副本以供访问吗?最好的方法是不在共享环境中使用文件,正是因为这样的问题。不能写入数据库吗?如果路径无效或磁盘已满,则该循环将非常有趣…尝试捕获更具体的条件。您现在正在忽略所有其他错误(并且将无限期地循环)。@Christophendebove,
数据库将无法避免我的等待问题。现在这句话完全错了。数据库处理锁定。几乎所有数据库引擎的默认设置都是乐观锁定。这一切都是自动完成的。
public void SomeWhereInYourWebServerApplication
{
FileSystemWatcher fsw = new FileSystemWatcher("tempfolder");
fsw.Created += fsw_Created;
// save new entries to tempfolder
}
void fsw_Created(object sender, FileSystemEventArgs e)
{
foreach (string file in Directory.GetFiles("tempfolder"))
{
try
{
string fileText = File.ReadAllText(file);
File.AppendAllText("myStorage.txt", fileText);
File.Delete(file);
}
catch
{
// for me it's ok when we try to append the file the next time
// something new is coming
}
}
}