简体   繁体   English

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

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

In Foo method, I create some task and I want to set a context in the main thread and access to it from other threads, is there any way I shared a context between my main thread and other threads than created in the main thread? 在Foo方法中,我创建了一些任务,我想在主线程中设置一个上下文并从其他线程访问它,是否有什么方法可以在我的主线程和其他线程(而不是在主线程中创建)之间共享上下文? I don't want to pass context to other threads and my preference is to set the context in a single point like in a custom lifestyle in IOC container for my execution context 我不想将上下文传递给其他线程,我的首选是将上下文设置为单点,例如在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>();
    }
}

You can do it like this: 你可以这样做:

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);
    }    
}

But you always need to remember about that different threads can operate with shared objects simultaneously, so if you want to use objects that threads can modify you must remember about synchronizing 但是您始终需要记住不同的线程可以同时对共享对象进行操作,因此,如果要使用线程可以修改的对象,则必须记住同步

You could use an Static method but be sure to apply a singleton pattern, or save the concurrency problem by any way 您可以使用静态方法,但请确保应用单例模式,或以任何方式保存并发问题

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>();
   }
}

Then you can call this method inside each task 然后,您可以在每个任务中调用此方法

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

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

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