设计线程安全类 [英] Designing a Thread Safe Class

查看:64
本文介绍了设计线程安全类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读MSDN文档时,它总是使您知道类是否是线程安全的.我的问题是如何设计一个线程安全的类?我不是在说用锁定来调用类,这是指我正在为Microsoft创建XXX class \ object,我想说的是线程安全",我需要做什么?

When reading the MSDN documentation it always lets you know if a class is thread safe or not. My question is how do you design a class to be thread safe? I am not talking about calling the class with locking I am meaning I am working for Microsoft create XXX class\object and I want to be say it is "Thread Safe" what would I need to do?

推荐答案

使类线程安全的最简单,最简单的方法是使其成为

The easiest and most foolproof way of making a class thread safe is to make it immutable. The beauty of it is that you don't ever have to bother with locking again.

配方:在C#中将所有实例变量设置为readonly(在Java中为final).

Recipe: Make all instance variables readonly in C# (final in Java).

  • 一个不变的对象一旦在构造函数中创建并初始化,就无法更改.
  • 不可变对象是线程安全的.期间.
  • 这与仅具有常量的类不同.
  • 对于系统的可变部分,您仍然需要考虑和处理锁定/同步属性.这是首先编写不可变类的原因.

也请参见此问题.

这篇关于设计线程安全类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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