Search code examples
c#boolean

Is there a shorthand way to say if a bool is already true don't assign false?


I already tried to search for this and couldn't find anything and not sure what this would be called. Boolean coalesce?

I have several methods being called in parallel each returns a bool indicating failure. Is there a way I can assign each of those to one bool such that if any one of them returns true the overall bool is true.

IE:

    Boolean exceptionOccurred = false;

    Parallel.Invoke(
       () => exceptionOccurred = MethodA(),
       () => exceptionOccurred = MethodB(),
       () => exceptionOccurred = MethodC(),
       () => exceptionOccurred = MethodD(),
    );

with that code as is, if Method A returned true and the rest of the methods returned false depending on which one returned first/last it would almost always get set to false. But I want to know if any of them return true.

One solution is to assign each to a unique bool and then check all of the bools. But I was hoping for something like a bitwise bool += operator that would not set exceptionOccurred to false if it was already true. Is there a way to do this?

I realize I could probably extend boolean to implement this myself, I was just wondering if there is already a way to do this?

I also realize the better solution is for each method to throw an exception and bubble them up but there are reasons I need to handle this differently, mainly that I want execution to continue but ultimately log an overall failure at the end.


Solution

  • Parallel writes to the same destination are only safe/useful if it's always the same result that is written to the destination. Luckily, your case is one of those exceptions. So the following is thread safe and will indicate whether at least one method failed. It's also the fastest because it does not need any synchronisation:

    () =>
    {
        var failure = MethodA();
        if (failure) exceptionOccurred = true;
    }
    

    a |= b or a = a || b is not safe. Consider the following:

    Thread1 reads a [false]
    Thread1 reads b [true]
    Thread2 reads a [false]
    Thread2 reads b [false]
    Thread1 writes true
    Thread2 writes false