简体   繁体   中英

WF: Check if the workflow application was cancelled from a custom activity

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM