vendredi 17 juin 2016

How to share the same context with different threads in multi-Command Pattern in C#?

There is an extended implementation of command pattern to support multi-commands (groups) in 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);

Now , the execution is like:

groups.Execute();

I am sharing the same context (ctx) object.

The execution plan of the web app needs to separate commandGroup1 and commandGroup2 groups in different thread. In specific, commandGroup2 will be executed in a new thread and commandGroup1 in the main thread.

Execution now looks like:

//In Main Thread
commandGroup1.Execute();

//In the new Thread
commandGroup2.Execute();

How can I thread-safely share the same context object (ctx), so as to be able to rollback the commandGroup1 from the new Thread ?

Aucun commentaire:

Enregistrer un commentaire