我怎么知道这个C#方法是线程安全的吗? [英] How do I know if this C# method is thread safe?

查看:199
本文介绍了我怎么知道这个C#方法是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个ASP.NET缓存项删除事件创建一个回调函数。

I'm working on creating a call back function for an ASP.NET cache item removal event.

文档说我应该叫一个对象或来电,我知道会存在(将在范围内),如一个静态方法上的一个方法,但它说我需要确保静态是线程安全的。

The documentation says I should call a method on an object or calls I know will exist (will be in scope), such as a static method, but it said I need to ensure the static is thread safe.

第1部分:有什么事我可以做,使一些例子是联合国线程安全的。

Part 1: What are some examples of things I could do to make it un-thread safe?

2部分:这是否意味着,如果我有

Part 2: Does this mean that if I have

static int addOne(int someNumber){
    int foo = someNumber;
    return foo +1; 
}

和我打电话Class.addOne(5);和Class.addOne(6); simutaneously,我可能会得到6或7取决于谁该调用首先将返回富? (即竞争条件)

and I call Class.addOne(5); and Class.addOne(6); simutaneously, Might I get 6 or 7 returned depending on who which invocation sets foo first? (i.e. a race condition)

推荐答案

这的 addOne 的功能确实是线程安全的,因为它不访问可能被另一个线程访问任何数据。局部变量不能线程之间,因为每个线程都有自己的堆栈共享。你必须确保,但是,该函数的参数是值类型,而不是引用类型。

That addOne function is indeed thread safe because it doesn't access any data that could be accessed by another thread. Local variables cannot be shared among threads because each thread gets its own stack. You do have to make sure, however, that the function parameters are value types and not reference types.

static void MyFunction(int x) { ... } // thread safe. The int is copied onto the local stack.

static void MyFunction(Object o) { ... } // Not thread safe. Since o is a reference type, it might be shared among multiple threads.

这篇关于我怎么知道这个C#方法是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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