0

では、まず背景について説明します。プロセス間のリーダー/ライター ロックが必要でした。ファイルを使用し、LockEx と UnlockEx を使用して最初のバイトをロックすることにしました。このクラスは、作成時にシステムの一時フォルダーにファイルを作成します。ファイルは、読み取り/書き込みアクセスと共有読み取り|書き込み|削除で作成されます。また、大量の一時ファイルを放置しないように、DeleteOnClose も指定します。明らかに、AcquireReader と AcquireWriter は適切なフラグを指定して LockEx を呼び出し、ReleaseLock は UnlockEx を呼び出します。
このクラスは、いくつかのインスタンスを実行できる小さなアプリケーションを使用してテストされており、完全に機能します。それを使用するアプリケーションに問題があり、別の小さなテスト アプリで再現することができました。擬似コードでは

InterProcessReaderWriter を作成する
ロックを取得せずに InterProcessReaderWriter を破棄する
リーダー ロックを取得する子プロセスを起動する

これを初めて実行すると、正常に動作します。最初の子プロセスがまだロックを保持している間に再度実行しようとすると、ファイルを開こうとすると UnauthorizedAccessException が発生します。
これは、共有違反ではなく権限の問題のようですが、このテスト ケースのすべてのプロセスは同じユーザーとして実行されています。ここに誰かアイデアがありますか?

ミューテックスとセマフォを使用して目的を達成することを提案する別の質問に気付きました。実装を変更する可能性がありますが、この問題の原因を知りたいです。

4

2 に答える 2

0

ファイル全体をロックしないのはなぜですか? 最初のバイトではなく。以下のサンプル クラスには、1 台のマシンだけに限定するのではなく、異なるマシンのプロセス間で動作できるという利点があります。

以下の lockfilehelper クラスを使用した簡単な例を次に示します。

Module Module1
    Sub Main()
        Using lockFile As New LockFileHelper("\\sharedfolder\simplefile.lock")
            If lockFile.LockAcquire(1000) Then
                ' Do your work here.
            Else
                ' Manage timeouts here.
            End If
        End Using
    End Sub
End Module

Helper クラスのコードは次のとおりです。

Public Class LockFileHelper
    Implements IDisposable
    '-------------------------------------------------------------------------------------------------
    ' We use lock files in various places in the system to provide a simple co-ordination mechanism
    ' between different threads within a process and for sharing access to resources with the same
    ' process running across different machines.
    '-------------------------------------------------------------------------------------------------
    Private _lockFileName As String
    Private _ioStream As IO.FileStream
    Private _acquiredLock As Boolean = False
    Private _wasLocked As Boolean = False
    Public Sub New(ByVal LockFileName As String)
        _lockFileName = LockFileName
    End Sub
    Public ReadOnly Property LockFileName() As String
        Get
            Return _lockFileName
        End Get
    End Property
    Public ReadOnly Property WasLocked() As Boolean
        Get
            Return _wasLocked
        End Get
    End Property
    Public Function Exists() As Boolean
        Return IO.File.Exists(_lockFileName)
    End Function
    Public Function IsLocked() As Boolean
        '-------------------------------------------------------------------------------------------------
        ' If this file already locked?
        '-------------------------------------------------------------------------------------------------
        Dim Result As Boolean = False
        Try
            _ioStream = IO.File.Open(_lockFileName, IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.None)
            _ioStream.Close()
        Catch ex As System.IO.IOException
            ' File is in used by another process.
            Result = True
        Catch ex As Exception
            Throw ex
        End Try

        Return Result
    End Function
    Public Sub LockAcquireWithException(ByVal TimeOutMilliseconds As Int32)
        If Not LockAcquire(TimeOutMilliseconds) Then
            Throw New Exception("Timed out trying to acquire a lock on the file " & _lockFileName)
        End If
    End Sub
    Public Function LockAcquire(ByVal TimeOutMilliseconds As Int32) As Boolean
        '-------------------------------------------------------------------------------------------------
        ' See have we already acquired the lock. THis can be useful in situations where we are passing
        ' locks around to various processes and each process may want to be sure it has acquired the lock.
        '-------------------------------------------------------------------------------------------------
        If _acquiredLock Then
            Return _acquiredLock
        End If

        _wasLocked = False
        Dim StartTicks As Int32 = System.Environment.TickCount
        Dim TimedOut As Boolean = False
        If Not IO.Directory.Exists(IO.Path.GetDirectoryName(_lockFileName)) Then
            IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(_lockFileName))
        End If
        Do
            Try
                _ioStream = IO.File.Open(_lockFileName, IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.None)
                _acquiredLock = True
            Catch ex As System.IO.IOException
                ' File is in used by another process.
                _wasLocked = True
                Threading.Thread.Sleep(100)
            Catch ex As Exception
                Throw ex
            End Try
            TimedOut = ((System.Environment.TickCount - StartTicks) >= TimeOutMilliseconds)
        Loop Until _acquiredLock OrElse TimedOut
        '-------------------------------------------------------------------------------------------------
        ' Return back the status of the lock acquisition.
        '-------------------------------------------------------------------------------------------------
        Return _acquiredLock
    End Function
    Public Sub LockRelease()
        '-------------------------------------------------------------------------------------------------
        ' Release the lock (if we got it in the first place)
        '-------------------------------------------------------------------------------------------------
        If _acquiredLock Then
            _acquiredLock = False
            If Not IsNothing(_ioStream) Then
                _ioStream.Close()
                _ioStream = Nothing
            End If
        End If
    End Sub
    Private disposedValue As Boolean = False        ' To detect redundant calls
    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                Call LockRelease()
            End If

            ' TODO: free shared unmanaged resources
        End If
        Me.disposedValue = True
    End Sub
#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region
End Class
于 2009-06-05T11:36:48.050 に答える
0

子プロセスが同じファイルに 2 回アクセスしようとしているように思えます。

一時ファイル名は一意ですか?

于 2009-05-09T21:24:28.357 に答える