相关疑难解决方法(0)

线程本地存储

将一些变量本地存储到每个线程的最佳方法是什么?

.net c#

30
推荐指数
4
解决办法
2万
查看次数

共享范围等待

我有一个UserScope类似于TransactionScope它的类,即它将当前状态存储在本地线程中.这当然不适用于调用await,TransactionScope直到TransactionScopeAsyncFlowOption.NET 4.5.1中都没有添加.

我可以使用什么替代线程本地,以便UserScope在单线程和多线程场景中使用相同的?(如果我安装了4.5.1,我会反编译以查看TransactionScope它是如何做的.)这是我所拥有的简化版本:

class User {
    readonly string name;

    public User(string name) {
        this.name = name;
    }

    public string Name {
        get { return this.name; }
    }
}

class UserScope : IDisposable {
    readonly User user;

    [ThreadStatic]
    static UserScope currentScope;

    public UserScope(User user) {
        this.user = user;
        currentScope = this;
    }

    public static User User {
        get { return currentScope != null ? currentScope.user : null; …
Run Code Online (Sandbox Code Playgroud)

c# multithreading task-parallel-library async-await

6
推荐指数
1
解决办法
561
查看次数