user3284707
user3284707

Reputation: 3341

Winforms asynchronous task, run multiple threads at once without blocking UI

I am new to Winforms coming from web and I am trying to get my head around asynchronous calls.

I have a dropdown, which I would like to call some methods to update 3 tabs on my page. I would like to do these asynchronously so it doesn't block the UI, and put a 'Loading...' message on each tab and load them all independently of each other, with the user being able to click through each tab still and see the progress of the loading.

I have the following, however this is still locking the UI, can someone point me in the right direction for where I am going wrong?

This is my dropdown event handler

    private async void ddlRoles_SelectedIndexChanged(object sender, EventArgs e)
    {
        await Task.Run(async () =>
        {
            await setTab1();
        });

        await Task.Run(async () =>
        {
            await setTab2();
        });

        await Task.Run(async () =>
        {
            await setTab3();
        });
    }

This is an example of one of my tasks which I would like to run asynchronously.

    private async Task setTab1()
    {
        if (tabl1Panel.InvokeRequired)
        {
            this.Invoke(new MethodInvoker(async delegate ()
            {
                await setTab1();
            }));
            return;
        }

        // LONG RUNNING CODE HERE...
    }

Upvotes: 1

Views: 1194

Answers (1)

Roger Hartley
Roger Hartley

Reputation: 684

The Invoke call you are using to run setTab1() means the code runs on the UI thread, hence why the UI locks up.

Try doing as much as possible within setTab1() without using Invoke(), and only use Invoke() to run code to update the UI once you have all the data you need.

Upvotes: 2

Related Questions