ca9163d9
ca9163d9

Reputation: 29227

The method is triggered twice from the control event handler?

I have some checkboxes in a group and the following is the event handler and the related method.

public async void CheckedChanged(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine($"Calling CheckedChanged {s.Name}: {s.CheckState}");
    await Filter();
}

public async Task Filter()
{
    System.Diagnostics.Debug.WriteLine($"Calling Filter");
    // ....
}

However, the following debug output shows the method Filter was called twice for each state change of the checkboxes.

Calling CheckedChanged CheckBox1: Checked
Calling Filter 
Calling Filter
Calling CheckedChanged CheckBox1: Unchecked
Calling Filter
Calling Filter 

The method Filter has some very expensive database calls and the SQL Profiler shows these calls are invoked twice too.


It turns out there method Filter was called in a Task.Run(...) and the debugger couldn't get the caller. The accepted answer helped to find it out.

Upvotes: 1

Views: 826

Answers (1)

RSadocchi
RSadocchi

Reputation: 72

Are you sure that Filter method is called only from CheckedChanged? Try something like this

    public async void CheckedChanged(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine($"Calling CheckedChanged {s.Name}: {s.CheckState}");
    await Filter(nameof("CheckedChanged"));
}

public async Task Filter(string caller = "undefined")
{
    System.Diagnostics.Debug.WriteLine($"Calling Filter from {caller}");
    // ....
}

Upvotes: 1

Related Questions