How to lock on an integer in C#?

后端 未结 14 2263
醉梦人生
醉梦人生 2020-12-05 14:44

Is there any way to lock on an integer in C#? Integers can not be used with lock because they are boxed (and lock only locks on references).

The scenario is as follo

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 14:48

    You want to make sure that a delete doesn't happen twice?

    CREATE PROCEDURE RemovePost( @postID int )
    AS
        if exists(select postID from Posts where postID = @postID)
        BEGIN
            DELETE FROM Posts where postID = @postID
            -- Do other stuff
        END
    

    This is pretty much SQL server syntax, I'm not familiar with MyISAM. But it allows stored procedures. I'm guessing you can mock up a similar procedure.

    Anyhow, this will work for the majority of cases. The only time it will fail is if two moderators submit at almost exactly the same time, and the exists() function passes on one request just before the DELETE statement executes on another request. I would happily use this for a small site. You could take it a step further and check that the delete actually deleted a row before continuing with the rest, which would guarantee the atomicity of it all.

    Trying to create a lock in code, for this use case, I consider very impractical. You lose nothing by having two moderators attempting to delete a post, with one succeeding, and the other having no effect.

提交回复
热议问题