在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);
}
}
但是你总是需要记住不同的线程可以同时使用共享对象,所以如果你想使用线程可以修改的对象,你必须记住synchronizing
您可以使用静态方法,但一定要应用单例模式,或以任何方式保存并发问题
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