Morpheus Morpheus - 2 years ago 105
C# Question

How to cancel backgroundworker from some part of method's code

I created Backgroundworker to operate on serial port which uses some methods provided by different classes. I'd like to cancel a worker each time an exception from those methods occurs.

Actually, I have some idea how to do it, using events, but I am afraid it's not optimal solution or a good practice. In that case I should firing event in each method, which is not efficient in my opinion.

For ex., one from methods,

ReceiveRecord
looks like that:

public string ReceiveRecord()
{
try
{
var receivedLine = _serial.ReadLine();
return receivedLine;
}
catch (TimeoutException exception)
{
MessageBox.Show($"Error was occured: \r\n {exception.Message}", "Timeout error",
MessageBoxButton.OK, MessageBoxImage.Error);
// HERE i want to fire worker cancellation

}
return String.Empty;
}


Worker calls that methods periodically.

I considered returning false, when errors occurs, but I don't have ANY idea, how to do it, if method returns
string
...

Are there any simple method to fire DoWork cancellation from the catch fragment of code?

Answer Source

Don't catch the exception in the method. Let the caller handle it in BackgroundWorker's RunWorkerCompleted event.

See Background worker exception handling

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download