I have a really trivial call to Activity.RegisterForStatusChange that results in a NullReferenceException. I'm doing something wrong, but am unable to find out what. My code:

WorkflowInstance workflow = runtime.CreateWorkflow(typeof(MyWorkflow.BlaWorkflow), workflowArgumentValues, workflowId);


Activity activity = workflow.GetWorkflowDefinition();

activity.RegisterForStatusChange(Activity.CancelingEvent, this);

What's wrong with this

The relevant part of the stack trace:

   at System.Workflow.ComponentModel.ActivityExecutorDelegateInfo`1..ctor(Boolean useCurrentContext, IActivityEventListener`1 eventListener, Activity contextActivity)
   at System.Workflow.ComponentModel.Activity.RegisterForStatusChange(DependencyProperty dependencyProp, IActivityEventListener`1 activityStatusChangeListener)


Thanks in advance,



Re: Windows Workflow Foundation NullReferenceException in RegisterForStatusChange

Vignesh Kannappan - MSFT

Hi Ronald -

when you do a instance.GetWorkflowDefinition() you do not get the actual running workflow, but the template workflow [think of template workflow as an in-memory instance used to clone actual running workflows from]. You can also verify that the returned value is a template workflow root by inspecting the ExecutionStatus property. It will always be Initialized --> never transitions to Executing/Canceling/Faulting/Closed states. Also notice that the ContextActivity property is null for the returned 'root' activity. This is the cause for the NullReferenceException you are seeing.

To accomplish what you are trying to do there are 3 options that come to mind:

1. If you want to subscribe to workflow's Completed/Terminated/Aborted/ etc events, please use the events on the workflow runtime.

2. For listening to status change events from other children activities or for canceling event of the workflow's root activity, you should really be using tracking service. Look at the tracking examples on how to do this.

3. You could use [not recommended, but something that came to my mind], workflow tracing events to listen for activities status change events. This is a bit tricky because you would need to listen to System.Workflow.Runtime name source for specific event trace. It usually looks like this: "System.Workflow.Runtime Information: 0 : Activity Status Change - Activity: <<activityname>> Old:<<ExecutionState>>; New:<<ExecutionState>>

I'd recommend reading this article:

Hope that clears some confusion,