I have a code Activity hosted inside a Windows Workflow Foundation Service, I want to terminate the workflow based on some values I am checking from the database. I don't want to use the Throw Exception method, and I need to do it from inside the "Code Activity" Code, not from the designer. I am still a beginner in WWF, I tried the below method, which is creating a workflow application, and initializing it on the current instance of the code activity, but it didn't work. I need to capture the parent workflow application of the current activity instance first, then call the Terminate method.
WorkflowApplication wfApp = new WorkflowApplication(this);
wfApp.Terminate("The following workflow is terminating");
Thanks for your help on this
To terminate gracefully, just use TerminateWorkflow as a child activity. This will invoke WorkflowApplication.Completed action.
public class CanceledActivity : NativeActivity
{
private readonly TerminateWorkflow terminateWorkflow = new TerminateWorkflow
{
Reason = "Reason why I'm terminating!"
};
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
metadata.AddImplementationChild(terminateWorkflow);
}
protected override void Execute(NativeActivityContext context)
{
context.ScheduleActivity(terminateWorkflow);
}
}
Or you can just throw an exception but this will invoke WorkflowApplication.OnUnhandledException instead.
public class CanceledActivity : NativeActivity
{
protected override void Execute(NativeActivityContext context)
{
throw new Exception("this will not gracefully terminate the workflow")
}
}
There're a bunch of other ways of doing it, also depending on what you want to do and when you want to do it. Keep in mind that workflow will only terminate when it can, due to its asynchronous nature.
You can put the WorkflowApplication into the application context extensions which will then be available through the ActivityContext class.
// Add the application to it's own context
_workflowApplication.Extensions.Add(_workflowApplication);
// Access the application in your activity
var application = context.GetExtension<WorkflowApplication>();
application.BeginTerminate(new WorkflowException(error), null, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With