繁体   English   中英

如何在一组线程之间共享执行上下文?

[英]How can I shared a execution context between a group of threads?

在Foo方法中,我创建了一些任务,我想在主线程中设置一个上下文并从其他线程访问它,是否有什么方法可以在我的主线程和其他线程(而不是在主线程中创建)之间共享上下文? 我不想将上下文传递给其他线程,我的首选是将上下文设置为单点,例如在IOC容器中为我的执行上下文定制生活方式中

public class IUserContext
{
    string UserName {get;}
    string Token {get;}
}

public void Foo()
{//I set the context data before calling the method
    foreach(...) {
        Task.Factory.StartNew(() =>method1);
    }

    void method1()
    {
         // context is null
         var context = Container.Resolve<IUserContext>();
    }
}

你可以这样做:

public class IUserContext
{
    public string  UserName 
    {
        get
        {
            return "user";
        }
    }
    public string Token 
    {
        get
        {
            return "token";
        }
    }
}

public class Program
{
    public static IUserContext context = new IUserContext();

    public static void Main()
    {

        for(int i = 0; i < 4; i++) 
        {            
            Task.Factory.StartNew(() => method1());
        }
    }

    public static void method1()
    {
        Console.WriteLine("I'm task #" + Task.CurrentId + " and I work with user " + context.UserName + " that have token " + context.Token);
    }    
}

但是您始终需要记住不同的线程可以同时对共享对象进行操作,因此,如果要使用线程可以修改的对象,则必须记住同步

您可以使用静态方法,但请确保应用单例模式,或以任何方式保存并发问题

public static void Foo()
{   
   //Singleton start
   private static ReadOnly Foo instance;
   private Foo() {}

   public static Foo Instance
   {
        get{
          if(instance == null){
             instance = new Foo();
             }
             return instance;
             }
   }
   //Singleton end

   public static void method1()
   {
        // context is null
        var context = Container.Resolve<IUserContext>();
   }
}

然后,您可以在每个任务中调用此方法

看看一个单例实例https://codeburst.io/singleton-design-pattern-implementation-in-c-62a8daf3d115

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM