仅当值相同时才锁定

仅当值相同时才锁定

本文介绍了仅当值相同时才锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个功能可以编辑Web服务中的数据库,而我只希望一个线程在尝试编辑同一行时一次执行.

If i have an function that edits the database in my webservice that i only want one thread to execute at one time if they try to edit the same row.

void EditCheck(long checkid)
    {

        if (isCheckCosed)
            throw new Exception("check is already closed");

        //do stuff

        //after i edit my check i want to close it.
        CloseCheck();
    }

我知道我可以锁定整个功能,但是随后我失去了性能,因为几乎没有不同的线程会尝试编辑相同的支票.

i know i can lock the whole function, but then i loose preformance because its almost never that different threads will try to edit the same check.

有没有办法只锁定具有相同checkid的其他线程?

is there a way to only lock out other threads that have the same checkid?

更新

我使用OleDbConnectionMySqlConnection

OleDbCommand oleDbCommand = AccessTrans != null ?
new OleDbCommand(sql, AccessConn, AccessTrans) : new OleDbCommand(sql, AccessConn);
oleDbCommand.ExecuteNonQuery();

MySqlCommand

然后我就使用普通的INSERT和UPDATE sql命令.然后检查交易是否存在.因此,如果您不希望在上层功能中进行交易,则可以使用此功能.

and then i jus use the normal INSERT and UPDATE sql commands.the and the transaction is checked if it is present or not. so this functions works if you want an transaction or not in your upper level function.

要从数据库中读取,我将填写DataTable

for reading from the database i'll fill DataTable

OleDbCommand oleDbCommand = AccessTrans != null ? new OleDbCommand(sql, AccessConn, AccessTrans) : new OleDbCommand(sql, AccessConn);
OleDbDataAdapter dAdapter = new OleDbDataAdapter();
dAdapter.SelectCommand = oleDbCommand;
dAdapter.Fill(dTable);
return dTable;

推荐答案

您可以使用ConcurrentDictionary将每个ID映射到可以锁定的对象:

You can use a ConcurrentDictionary to map each id to an object that you can lock on:

public class Foo
{
    private ConcurrentDictionary<long, object> dictionary =
        new ConcurrentDictionary<long, object>();

    private void EditCheck(long checkid)
    {
        var key = dictionary.GetOrAdd(checkid, new object());
        lock (key)
        {
            //Do stuff with key
        }
    }
}

这篇关于仅当值相同时才锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:48