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



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

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

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

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

最新更新