views:

18

answers:

1

Hi, How can i check from my NativeActivity if the 'Cancel' method of the workflow application was invoked?

I tried to use the 'IsCancellationRequested' property of the context but it doesn`t much.

Here is my sample:

public class Program
{
    static void Main(string[] args)
    {
        ManualResetEventSlim mre = new ManualResetEventSlim(false);
        WorkflowApplication app = new WorkflowApplication(new Sequence() { Activities = {new tempActivity(), new tempActivity() } });
        app.Completed += delegate(WorkflowApplicationCompletedEventArgs e)
        {
            mre.Set();
        };
        app.Run(TimeSpan.MaxValue);
        Thread.Sleep(2000);
        app.BeginCancel(null,null);
        mre.Wait();
    }
}

public class tempActivity : NativeActivity
{
    protected override void Execute(NativeActivityContext context)
    {
        Console.WriteLine("Exec tempActivity");
        for (int i = 0; i < 10; i++)
        {
            Thread.Sleep(1000);
            Console.Write(".");
            if (context.IsCancellationRequested)
                return;
        }
    }
}

Thanks!

A: 

Pretty much everything in workflow is scheduled and executed asynchronously. This includes cancellation so blocking in the Executes makes sure the cancel request is never processed.

You need to write the activity something like this:

public class tempActivity : NativeActivity
{
    private Activity Delay { get; set; }
    private Variable<int> Counter { get; set; }

    protected override void CacheMetadata(NativeActivityMetadata metadata)
    {
        Counter = new Variable<int>();
        Delay = new Delay() { Duration = TimeSpan.FromSeconds(1) };

        metadata.AddImplementationChild(Delay);
        metadata.AddImplementationVariable(Counter);

        base.CacheMetadata(metadata);
    }


    protected override void Execute(NativeActivityContext context)
    {
        OnCompleted(context, null);
    }

    private void OnCompleted(NativeActivityContext context, ActivityInstance completedInstance)
    {
        var counter = Counter.Get(context);
        if (counter < 10 && !context.IsCancellationRequested)
        {
            Console.Write(".");
            Counter.Set(context, counter + 1);
            context.ScheduleActivity(Delay, OnCompleted);
        }
    }
}
Maurice
I don`t expect that the cancel operation will abort the running thread of the execute method but still i want to get some kind of notification that the workflow application was cancelled. why the 'IsCancellationRequested' property is not set to true?
Avi K.
It is set to true as soon as you give the runtime a change to do so. As long as you are not returning from the Execute() the runtime doesn't get a change to do anything.
Maurice
I Still don`t understand why (it could not run from a different thread?). maybe you could explain a bit more or add an additional links. thanks!
Avi K.