Click here to Skip to main content
15,868,164 members

Response to: multiple exe on a lan shared a global variable

Revision 2
There is no built-in solution for this approach. But you can use the database (a dedicated table, or a shared table that-s involved in this lock logically). Assuming you use SQL Server proper lock hint and transaction isolation can be used to achieve the same goal (see details here[^]) - see SERIALIZABLE. You might find more details in these articles: Using Transactions in ADO.NET[^], Locks and Duration of Transactions in MS SQL Server[^].
The idea: if an object is locked, only one application can gain access to it, and you can use this behavior to control weather a form can or can not be displayed.
If you take this path, be aware to test it in cases when on client gathered the lock, but was cut from the server (killed), you might need some fine-tuning. But even so, this approach is easier to code than other distributed IPC.

Update:
Here is the scenario you can use to gain and test exclusive access to any table (a production one, or a dedicated one) - this is the T-SQL version, but it is as simple to do it in C# also.
Ok, first of all, before you want to show that editor form, issue this script (or it's c# equivalent):
SQL
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
GO
SET LOCK_TIMEOUT 0;
GO
BEGIN TRANSACTION;
GO
UPDATE T SET X=X WHERE X<>X;
GO

Please remark the dummy DML statement: it does nothing but locks the table T.

After the user finished editing, issue the actual update DML statements, and simply commit the transaction:
SQL
COMMIT TRANSACTION;
GO


What happens? With serializable transaction, and the update issued the client will gain exclusive access to the T for the whole transaction - until it is committed, rolled back or canceled by the server itself due to lost connection. And because it is a zero lock wait timeout, the second application instance trying to get the same lock, will fail immediately. You will get an exception on client side, that you can use to warn the user to come back later, since the table he wants to edit is edited by somebody else. After commit (or rollback) the lock is released, so an other instance can get the lock and so on.

For C# version, see SqlConnection.BeginTransaction[^], as I know SET LOCK_TIMEOUT has to be issued as a nonquery command.

You can also fine-tune the timeout value if you can allow waiting. By default it is -1 (infinite) - thus any lock could hang your application.
Posted 22-Sep-12 2:29am by Zoltán Zörgő.
Tags: ,