如何使物体线程在C#? [英] How to make objects Threadsafe on c#?

查看:132
本文介绍了如何使物体线程在C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求在大多数情况下,线程的应用程序。大多数时候,因为对象被更新之前,它执行的每个线程我会遇到错误或错误的价值观。你的任何建议,如何让对象是线程安全的,并确保对象有正确的每个线程?我应该让我的变量静态的?

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 it's execution for each thread. Do you any suggestion how to make objects be thread safe and making sure that objects have the correct for each thread? Should I make my variables static?

您的回答是极大的赞赏。

Your answer is greatly appreciated.

最好的,

推荐答案

考虑使用的,你需要做线程安全的任何资源锁定声明。

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

这些都是可以并行操作过程中保护您的资源的两种基本方式。还有很多其他的方法,如互斥,sempahores,有条件的读/写锁等。

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.

这篇关于如何使物体线程在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆