How to make objects Threadsafe on c#?

后端 未结 3 513
灰色年华
灰色年华 2021-01-07 06:30

I have a an application that requires threading in most cases. Most of the time I will encounter errors or wrong values because the object was updated prior to its execution

3条回答
  •  情话喂你
    2021-01-07 07:10

    Look into using the lock statement for any resources that you need to make thread safe.

    http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

    class Account
    {
        decimal balance;
        private Object thisLock = new Object();
    
        public void Withdraw(decimal amount)
        {
            lock (thisLock)
            {
                if (amount > balance)
                {
                    throw new Exception("Insufficient funds");
                }
                balance -= amount;
            }
        }
    }
    

    This would be my first step. Also you can look into the Monitor class.

    http://msdn.microsoft.com/en-us/library/system.threading.monitor.aspx

    These are the two basic ways that you can protect your resources during concurrent operations. There are many other ways such as mutexes, sempahores, conditional read/write locks,etc.

提交回复
热议问题