C#multiprocess访问同一个文件

use*_*139 -2 c# asp.net

我在项目上工作,包括一个Windows客户端应用程序和ASP网页...

Windows应用程序在网页服务器上执行.Windows客户端和ASP网页在同一台服务器上协同工作,并在同一个共享文件上工作...

我想安全访问这些文件,windows app等待网页完成文件和/或网页上的工作等待windows app完成这些文件的工作..

EventWaitHandle waithandle=new EventWaitHandle(true, EventResetMode.AutoReset, "SI_handle");在Windows应用程序和ASP网页中使用

并且在ASP网页和Windows应用程序上使用waithandle.WaitOne();之前访问文件和waithandle.Set();完成工作后的文件.

我的问题是Windows应用程序o网页永远等待waithandle.WaitOne();和应用程序或网页冻结它.

我错了什么?

像这样的窗口或网页代码:

if (File.Exists(xml_path))
{
    waithandle.WaitOne();
    // work on file
    waithandle.Set();
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 6

为什么不简单地使用操作系统来帮助您,因为您可以通过指定打开指定不应共享访问的文件FileShare.None.如:

try
{
    using (var stream = File.Open("my file name", FileMode.Open, FileAccess.ReadWrite, FileShare.None))
    {
        // Do with it what you want.
    }
}
catch (IOException ex)
{
    if (IsFileLocked(ex)
        // try later.
    else
        // report error.
}

...

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;

private static bool IsFileLocked(Exception exception)
{
    int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
    return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}
Run Code Online (Sandbox Code Playgroud)