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

时间:2019-03-13 16:54:53

标签: c# multithreading ioc-container

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

app.get(/.*html$/, (req, res) => {
  // do what you need
})

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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

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

答案 1 :(得分:0)

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

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