使用NativeActivity进行异常处理

时间:2010-08-24 18:48:25

标签: workflow-foundation-4

我正在使用一个名为Body的子活动和一个名为OnFault的ActivityAction的NativeActivity,这是我的代码:

[Designer(typeof(RetryDesigner))]
public sealed class Retry : NativeActivity {

    public Activity Body { get; set; }
    public ActivityAction<Exception> OnFault { get; set; }

    protected override void CacheMetadata(NativeActivityMetadata metadata) {
        metadata.AddChild(Body);
        metadata.AddDelegate(OnFault);
        base.CacheMetadata(metadata);
    }

    protected override void Execute(NativeActivityContext context) {
        context.ScheduleActivity(Body, OnBodyCompleted, OnBodyFaulted);
    }

    void OnFaultCompleted(NativeActivityContext context, ActivityInstance instance) {
        context.ScheduleActivity(Body);
    }

    void OnBodyCompleted(NativeActivityContext context, ActivityInstance instance) {
    }

    void OnBodyFaulted(NativeActivityFaultContext faultContext, Exception propagatedException, ActivityInstance propagatedFrom) {
        faultContext.HandleFault();

        if (OnFault != null) {
            faultContext.ScheduleAction<Exception>(OnFault, propagatedException, OnFaultCompleted);
        }
    }
}

我的主要看起来像这样:

    static void Main(string[] args) {

        Variable<Exception> ex = new Variable<Exception>();
        DelegateInArgument<Exception> exception = new DelegateInArgument<Exception>();

        Retry retry = new Retry {
            Body = new Sequence {
                Variables = { ex },
                Activities = {
                    new Assign<Exception> {
                        To = new OutArgument<Exception>(ex),
                        Value = new InArgument<Exception>((env) => new Exception("test"))
                    },
                    new Throw {
                        Exception = ex
                    }
                }
            },
            OnFault = new ActivityAction<Exception> {
                Argument = exception,
                Handler = new Sequence {
                    Activities = {
                        new WriteLine{
                            Text = new InArgument<string>(env =>
                             exception.Get(env).Message)
                        }
                    }
                }
            }
        };

        var workflow = new WorkflowInvoker(retry);
        workflow.Invoke();

        Console.WriteLine();
    }

问题是异常不会在OnBodyFaulted回调中停止,而是作为未处理的扩展显示在主要上。

如何在OnBodyFault回调中停止Exception,工作流程中是否有任何状态或属性可以执行此操作?

1 个答案:

答案 0 :(得分:1)

问题是在OnFaultCompleted()中你再次调用了context.ScheduleActivity(Body)。这次没有故障处理程序,导致同一故障再次发生,完整的工作流程出现故障。