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

查看:213
本文介绍了我如何知道这个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部分:

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

Part 2: Does this mean that if I have

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

我调用Class.addOne和Class.addOne(6);同时,我可能得到6或7返回取决于谁调用集foo第一谁? (即竞争条件)

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天全站免登陆