简体   繁体   English

用户锁定线程

[英]Locking a thread by user

I need a way to lock c# threads by user 我需要一种方法来按用户锁定c#线程

I have my data object and I create new instance for every user. 我有我的数据对象,我为每个用户创建新的实例。 Every user has several threads that use this object and in IO operations I want to lock this object instance for this user only. 每个用户都有几个使用此对象的线程,在IO操作中,我只想为此用户锁定此对象实例。 Using simple Lock {} is locking all the object instances, there for blocking other user. 使用简单的Lock {}锁定所有对象实例,用于阻止其他用户。

I need some simple solution. 我需要一些简单的解决方案

Edit 编辑

I build new instance of MyDataObj per user; 我为每个用户构建了MyDataObj新实例; Then run job that updating some data in MyDataObj every minute; 然后运行每分钟更新MyDataObj一些数据的工作; Using lockObj as lock, lock the data to all the users (Although it's not static Variables) I need only to lock the data to the current user 使用lockObj作为锁,将数据锁定到所有用户(尽管它不是静态变量),我只需要将数据锁定到当前用户

this is the code sample 这是代码示例

public sealed class MyDataObj
{
    private static readonly Dictionary<object, MyDataObj> _instances = new Dictionary<object, MyDataObj>();
    public object lockObj = new object();
    public bool jobRunning = false;
    private string data = string.Empty;
    //// --------- constractor -------------------
    private MyDataObj(int key)
    {
        LoadMyDataObj(key);
    }

    public static MyDataObj GetInstance(int key)
    {
        lock (_instances)
        {
            MyDataObj instance;
            if (_instances.TryGetValue(key, out instance))
            {
                instance = _instances[key];
                return instance;
            }
            instance = new MyDataObj(key);
            return instance;
        }
    }

    private void LoadMyDataObj(int key)
    {
        // get the data from db

    }


    public void UpdateMyData(string newData)
    {
        lock (lockObj)
        {
            this.data = newData;
        }
    }
    public string ReadMyData()
    {
        lock (lockObj)
        {
            return this.data;
        }
    }



    public class ActionObject
    {
        MyDataObj myDataObj;
        int UserID;
        //// --------- constractor -------------------
        public ActionObject(int userid)
        {
            this.UserID = userid;
            myDataObj = MyDataObj.GetInstance(userid);
            if (!myDataObj.jobRunning)
            {
                jobs jbs = new jobs(myDataObj);
                System.Threading.Thread RunJob = new System.Threading.Thread(new System.Threading.ThreadStart(jbs.dominutesAssignment));
                RunJob.Start();
                myDataObj.jobRunning = true;
            }
        }
        public ActionObject()
        {
            myDataObj = MyDataObj.GetInstance(this.UserID);
            myDataObj.UpdateMyData("some data");
        }
    }


    public class jobs
    {
        MyDataObj myDataObj = null;

        public jobs(MyDataObj grp)
        {
            this.myDataObj = grp;
        }
        public void dominutesAssignment()
        {
            while (true)
            {
                myDataObj.ReadMyData();
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

I need a way to lock c# threads by user. 我需要一种由用户锁定c#线程的方法。 I have my data object and I create new instance for every user 我有数据对象,并为每个用户创建了新实例

Create one lock per user. 为每个用户创建一个锁。 Or if the user exists longer than the threads: Use the user object as the lock. 或者,如果用户存在的时间超过线程的时间:使用用户对象作为锁。

lock (userOrTheUserObject)
{
    //Do some op
}

Every user has several threads that use this object and in IO operations 每个用户都有多个线程使用此对象并在IO操作中

That sounds more like you should use asynchronous IO instead of creating several threads (which will be less effecient) 这听起来更像是您应该使用异步IO而不是创建多个线程(这样效率较低)

I want to lock this object instance for this user only. 我只想为此用户锁定此对象实例。 Using simple Lock {} is locking all the object instances, there for blocking other user. 使用简单的Lock {}锁定所有对象实例,用于阻止其他用户。

If the object is shared between all users you HAVE to lock it using lock . 如果对象在所有用户之间共享,则必须使用lock对其进行lock The lock won't be very effective otherwise. 否则锁定不会很有效。 The other object is to redesign the object to now be shared. 另一个目标是重新设计现在要共享的对象。

I need some simple solution. 我需要一些简单的解决方案

There are no simple threading solutions. 没有简单的线程解决方案。

You can use Monitor . 你可以使用Monitor In this sample anyone but user 1 can execute DoIt method concurrently. 在此示例中,除用户1之外的任何人都可以同时执行DoIt方法。 While user 1 executing DoIt no one can enter it. 当用户1执行DoIt时,没有人可以输入它。 A weak point is if user 1 tries to execute DoIt when user 2 already executing it, user 2 continues its execution. 一个弱点是,如果用户1在用户2已经执行DoIt时尝试执行DoIt,则用户2继续执行它。 Also you have to handle exceptions properly otherwise there may be dead locks. 此外,您必须正确处理异常,否则可能会出现死锁。

private static readonly object lockObj = new Object();

public void Do(int userId)
{
     Monitor.Enter(lockObj);

     if (userId != 1)
          Monitor.Exit(lockObj);

     try
     {
        DoIt();
     }
     finally 
     {
         if (userId == 1)
             Monitor.Exit(lockObj);
     }
}

public void DoIt()
{
    // Do It
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM