Home > database >  C# Asynchronous not working (async await)
C# Asynchronous not working (async await)

Time:02-05

I try to create a program checking in a lot of PDF. It can be done from a network drive and take few minutes. The application freeze all during the process and I want to avoid that.

I searched in a lot of posts and videos but I failed to implement it in my program. I tried this code to understand how it works but it failed to...

    async private void button1_Click(object sender, EventArgs e)
    {
        rtbx.AppendText($"Processing...\n");

        // This webswite takes 1-2s to be loaded
        await HeavyWork(@"https://aion.plaync.com/");

        rtbx.AppendText($"End.\n");
    }



    public Task HeavyWork(string url)
    {

        List<string> lesinfos = new List<string>();

        while (checkBox1.Checked == false)
        {

            using (WebClient web1 = new WebClient())
            {
                lesinfos.Add(web1.DownloadString(url));
            }

            rtbx.AppendText($"{lesinfos.Count}\n");
            this.Refresh();
        }

        rtbx.AppendText($"Done !\n");
        return Task.CompletedTask;
    }

When I click the button, I am never able to clic in the checkbox and the IU never respond.

Ty for your help :)

CodePudding user response:

Taking into account that you are forced to use a synchronous API, you can keep the UI responsive by offloading the blocking call to a ThreadPool thread. The tool to use for this purpose is the Task.Run method. This method is specifically designed for offloading work to the ThreadPool. Here is how you can use it:

public async Task HeavyWork(string url)
{
    List<string> lesinfos = new List<string>();
    using (WebClient web1 = new WebClient())
    {
        while (checkBox1.Checked == false)
        {
            string result = await Task.Run(() => web1.DownloadString(url));
            lesinfos.Add(result);
        }
        rtbx.AppendText($"{lesinfos.Count}\n");
        this.Refresh();
    }
    rtbx.AppendText($"Done !\n");
}

Notice the async keyword in the signature of the HeavyWork method. Notice the await before the Task.Run call. Notice the absence of the return Task.CompletedTask line at the end.

If you are unfamiliar with the async/await technology, here is a tutorial to get you started: Asynchronous programming with async and await.

CodePudding user response:

Try using DownloadStringAsync(...) with an `await (see example below).

public Task HeavyWork(string url)
{

    List<string> lesinfos = new List<string>();

    while (checkBox1.Checked == false)
    {

        using (WebClient web1 = new WebClient())
        {
            lesinfos.Add(await web1.DownloadStringAsync(url));
        }

        rtbx.AppendText($"{lesinfos.Count}\n");
        this.Refresh();
    }

    rtbx.AppendText($"Done !\n");
    return Task.CompletedTask;
}
  •  Tags:  
  • Related