C#C
C#3y ago
The Don

✅ Is use of IDisposable, using keyword for a UI wait indicator incorrect?

I have a wait indicator for WPF that implements
IDisposable
. When creating a new object of this
IDisposasble
implementation wrapped in a
using
keyword, it initializes the wait indicator on my WPF screen. Upon disposing, the wait indicator disappears.

This is the code I used before implementing
IDisposable
:

async Task LongRunningTask1()
{
    _waitIndicator.Show("Waiting")

    await Task1();

    if(cancel)
    {
        _waitIndicator.Hide(); // Accounts for early return

        return;
    }

    await Task2();

    _waitIndicator.Hide()
}


Here I have an early return, so I have to call
waiter.hide()
twice. This is a simple case, so it may seem trivial to call it more than once, but this can cause problems when the code is more complicated. Forgetting to
hide()
will obviously hang the UI.

On the other hand, using this code:

async Task LongRunningTask2()
{
    using(new _waitIndicator.Show("Waiting"))
    {
        await Task1();

        if(cancel)
        {
            // No need to "hide" the wait indicator, instead, it is done when the
            // using statement ends.
            return; 
        }

        await Task2();
    }
}


Seems more simplistic and readable. I am wondering if there are any problems with this. If so, are there any alternatives to this?

Thanks!
Was this page helpful?