c# - 单例线程安全

标签 c# singleton-methods

我的问题与类函数的线程安全有关。这是我为了更好地理解而拼凑的一些测试代码。

public sealed class Singleton
{  
    public static Singleton Instance { get { return _lazyInit.Value; } }

    private static readonly Lazy<Singleton> _lazyInit = new Lazy<Singleton> (() => new Singleton());

    public long ExecuteAlgorithm(int n)
    {
            n += 2;
            return new Algorithm().Fibonacci(n);
    }
}

public class Algorithm
{
    public long Fibonacci(int n)
    {
        long a = 0;
        long b = 1;

        for (long i = 0; i < n; i++)
        {
            long temp = a;
            a = b;
            b = temp + b;
        }
        return a;
    }
}

类 Singleton 的创建是安全的,但我的问题是关于函数 ExecuteAlgorithm 的使用。多线程使用 ExecuteAlgorithm() 安全吗?

我的理解是,它应该不会导致任何竞争条件,因为创建的每个线程都有自己的堆栈,局部函数变量将被压入其中,然后算法实例的创建将在应用程序范围的堆中创建.

我的理解正确吗?

最佳答案

没错。 ExecuteAlgorithm() 无法访问共享状态,因此不可能出现线程问题。

但是 ExecuteAlgorithm() 也可能是静态的,至少就多线程安全而言是这样。 Fibonacci() 也是如此。

关于c# - 单例线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700791/

相关文章:

c# - 错误 : the property name 'firstname' specified for the type microsoft. crm.sdk.data.services 无效

c# - MonoTouch 中自定义 TabBarController 中的 ViewDidLoad 中的公共(public)属性始终为 null

c# - 将 GridView 中不可见的列导出到 Excel

java - Spring MVC 单例 Controller - 多个下载请求

ruby - 是否可以使用 block 定义 Ruby 单例方法?

c# - 从 C# .NET 调用使用 C 样式数组作为参数的 C 方法

c# - 如何使用 ADO.NET 创建数据源而不是读取和操作数据源

ruby - Ruby 中的单例方法有任何异常(exception)吗?

ruby - 通过include添加类方法