C# Check folder avoid blocking UI

This is my code in order to check if a directory exists. As the directory might be also a network folder, I put a timeout. The code works but it blocks my UI:

    private delegate bool DirectoryExistsDelegate(string folder);
    public static bool DirectoryExists(string path, int timeout = 2000)
    {
        bool retValue = false;
        try
        {
            DirectoryExistsDelegate callback = new DirectoryExistsDelegate(Directory.Exists);
            IAsyncResult result = callback.BeginInvoke(path, null, null);
            if (result.AsyncWaitHandle.WaitOne(timeout, false))
                return callback.EndInvoke(result);
            return false;
        }
        catch
        {
            return false;
        }
    }

How to solve this?

728x90

1 Answers C# Check folder avoid blocking UI

Your method doesn't return until the Exists call is fully complete, so it will always block the UI. You've essentially started an asynchronous operation, but then sit around twiddling your thumbs waiting for it to complete.

As Dmitry Bychenko pointed out, you can do this in another thread and handle it very cleanly using async, await and Task.Run. To do this you should also make the event handler that's calling this method async, e.g.:

// An async event handler
public async void Button_Click(...)
{
    ...
    var exists = await DirectoryExists(myPath);
    ...
}

public async Task<bool> DirectoryExists(string path)
{
    return await Task.Run<bool>(() => Directory.Exists(path));
}

4 months ago