简体   繁体   中英

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? 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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