【发布时间】:2016-10-19 18:54:30
【问题描述】:
命令模式有一个扩展的实现来支持 C# 中的多命令(组):
var ctx= //the context object I am sharing...
var commandGroup1 = new MultiItemCommand(ctx, new List<ICommand>
{
new Command1(ctx),
new Command2(ctx)
});
var commandGroup2 = new MultiItemCommand(ctx, new List<ICommand>
{
new Command3(ctx),
new Command4(ctx)
});
var groups = new MultiCommand(new List<ICommand>
{
commandGroup1 ,
commandGroup2
}, null);
现在,执行是这样的:
groups.Execute();
我正在共享同一个 context (ctx) 对象。
web应用的执行计划需要分开
commandGroup1 和 commandGroup2 组在不同的线程中。具体来说,commandGroup2 将在新线程中执行,commandGroup1 在主线程中执行。
现在的执行如下:
//In Main Thread
commandGroup1.Execute();
//In the new Thread
commandGroup2.Execute();
我如何线程安全共享相同的context object (ctx),以便能够从新线程回滚commandGroup1?
t.Start(ctx); 够用还是我必须使用锁之类的?
部分代码实现示例为here
【问题讨论】:
-
这取决于 ctx 在命令中的使用方式。如果它同时使用(即两个线程可以同时访问它) - 例如,您可以在两个命令中锁定 ctx 变量本身。一般来说,您的问题不是很清楚,如果您提供如何使用这些多命令的具体示例,可能会更好。
-
你查看并发包了吗?
标签: c# multithreading design-patterns command-pattern