哪些功能使一个类是线程安全的吗? [英] Which features make a class to be thread-safe?

查看:242
本文介绍了哪些功能使一个类是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MSDN这样描述了一些.NET类:

In MSDN some .NET classes described like this:

:此类型是线程安全

公开静态(共享在Visual Basic中)这种类型的成员都是线程安全的实例成员都不能保证是线程安全的。

我的问题是哪些功能使一个类是线程安全的吗?

My question is which features make a class to be thread-safe?


  • 有没有什么标准,建议或线程安全的编程指南?

  • Is there any standard, recommendation or guidelines for thread-safety programming?

当我使用锁(C#)的关键字,这意味着我的课是线程安全与否?

When I use lock(C#) keyword, it means my class is thread-safe or not?

如何评价我一类的线程安全?是否有以确保一类是100%线程安全的任何测试

How to I evaluate thread-safety of a class? Is there any TESTS to be sure that a class is 100% thread safe?

?例如:

public class MyClass
{
    public void Method()
    {
        lock (this)
        {
            // Now, is my class 100% thread-safe like Microsoft classes?
        }
    }
    type m_member1;
    type m_member2;
}



感谢

thanks

推荐答案

一个类通常被认为是线程安全的,如果它的方法可以被多个线程同时不破坏类的状态或引起意外的副作用调用。有很多原因,一类可能不是线程安全的,但也有一些常见的原因是,它包含了将在并发访问被破坏的一些状态。

A class is generally considered thread-safe if its methods can be invoked by multiple threads concurrently without corrupting the state of the class or causing unexpected side-effects. There are many reasons why a class may not be thread safe, although some common reasons are that it contains some state that would be corrupted on concurrent access.

有一个数字的方式,使一个类线程安全的:

There are a number of ways to make a class thread-safe:


  1. 请它不可变的,如果一个类不包含任何状态下,它可以安全地从多个同时使用线程。

  2. 使用锁定减少并发。然而,这是没有线程安全保障,它只是确保代码块将不被同时由多个线程执行。如果状态被存储方法调用之间,这仍然可能会变得不一致。

您如何创建一个线程安全的类实际上取决于你想要什么做有问题的类。

How you create a thread-safe class really depends on what you want to do with the class in question.

您还需要问问自己,我需要让我的线程安全类?最UI框架的一种常见的模型是有一个单一的UI线程。例如在的WinForms,WPF和Silverlight的大多数代码将从UI线程,这意味着你不必建造线程安全到您的类来执行。

You also need to ask yourself, do I need to make my class threadsafe? a common model of most UI frameworks is that there is a single UI thread. For example in WinForms, WPF and Silverlight the majority of your code will be executed from the UI thread which means you do not have to build thread-safety into your classes.

这篇关于哪些功能使一个类是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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