Link to home
Start Free TrialLog in
Avatar of PSernz
PSernz

asked on

Controlling Simultaneous read/writes to a file

I want to carry a transaction number in a file shared by a number of processes.

Each process will periodically update this transaction number however I want to be able to control contention on this file.
In C or C++ you can use the Lock directive to perform an exclusive lock of a portion of the file such that if any other process attempts a simultaneous lock, the second process will be placed in CPU wait until the lock is removed by the first process.

A process will lock the file, read and increment the transaction number before writing the new transaction number and finally unlocking the file.

What directives are used in C#.NET to accomplish an exclusive lock on a file that will place any other bidding processes on hold until the first lock is removed.

Thanks.

PSernz
Avatar of strickdd
strickdd
Flag of United States of America image

You can use event handlers that fire when one of your processes has a "lock" then then it is "unlocked" send another event so the next write/read can take place.
Avatar of devsolns
devsolns

Define "process".  Are we talking literal processes with different application domains?  If so "events" obviously wont work.

If you've done it in C++ and know how then why dont you just do the same?

Use P/Invoke to call those same exactly win32 dll.

[DllImport(KERNEL32, SetLastError=true)]
public static extern bool LockFile(IntPtr handle, long offset, long count);
ASKER CERTIFIED SOLUTION
Avatar of mastoo
mastoo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I should clarify, [DllImport("kernel32.dll", SetLastError = true)]
"A named mutex is an easy way to coordinate processes."

-agree
Avatar of PSernz

ASKER

I don't want to go back to C++ if I can avoid it.

Can someone provide an example of a named mutex used to achieve a process lock.
Yes my processes are different application domains.

Thanks.
your not going "back to c++".  again you can call win32 dll from c# effortlessly.