1

I have a 'stop process button' ToolStripButton on a parent MDI form. From a child form I start a process on a background thread using TPL, and get the tasks return status and changes the UI accordingly. The Click event of the 'stop process button' is dealt with using a delegate which works well. However, I cannot seem to remove it. Please see the code below:

private void buttonRunValid_Click(object sender, EventArgs e)
{
    // UI.
    mainForm.stopButton.Enabled = true;

    // Thread cancellation.
    cancelSource = new CancellationTokenSource();
    token = cancelSource.Token;

    // Start new parallel task and pass uiScheduler.
    Task<bool> asyncValidationTask = new Task<bool>(state => 
        asyncRunValidationProcess(uiScheduler, token, ref timeSpan), 
            "Running Validation Process");
    asyncValidationTask.Start();

    // Callback for cancellation.
    asyncValidationTask.ContinueWith(task =>
    {
        // Do some error checking with task.Status...

        // Remove delegate (back on uiThread).
        mainForm.stopButton.Click -= delegate
            {
                UtilsTPL.CancelRunningProcess(ref mainForm, asyncValidationTask, cancelSource); 
            };
        return;
    }, TaskScheduler.FromCurrentSynchronizationContext());

    // Handle the cancellation.
    mainForm.stopButton.Click += delegate 
        { 
            UtilsTPL.CancelRunningProcess(ref mainForm, asyncValidationTask, cancelSource);
        };
    return;
}

where mainForm is the MdiParent and stopButton is an accessor to the mainForm's ToolStripButton which fires the cancel/stop process event.

I am attempting to remove the delegate in the tasks continuation method but this is not working. I have also tried to loop through all events contained by the ToolStripButton using reflection:

FieldInfo fieldInfo = 
    typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic); 
object obj = fieldInfo.GetValue(_stripButton); 
PropertyInfo propertyInfo = 
    _stripButton.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); 
EventHandlerList list = (EventHandlerList)propertyInfo.GetValue(_stripButton, null); 
list.RemoveHandler(obj, list[obj]); 

This also does not work. How can I remove the EventHandler/delegate?

1 Answer 1

3

Using anonymous methods or lambdas for event handlers is problematic for this reason. The delegate you're adding and the one you're trying to remove are different instances (despite containing identical code). The solution to this problem is either to save a reference to the delegate you're adding, or to use a named method instead. See this question for details.

However, I'd ask why you're removing the event handler in the first place. If it's to stop your handler code from running while a particular process is in progress, I'd prefer disabling the button, then re-enabling it once processing has finished.

1
  • The MdiParent contains a ToolStrip that hosts a generic stop button. I have many processes that run with dirrerent Tasks and this button is to be used to stop any of them according to which Task is passed to the cancel method/delegate.
    – MoonKnight
    Mar 13, 2012 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.