Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Async task blocking UI

Hello esteemed colleagues, I need to save to a text file every time I get a new message from my serial port into my richtext box. I’m trying to use async and await it won’t block the UI while saving the text file, but unfortunately I’m doing something wrong because it still blocking. Please, what am I doing wrong?

Text changed method from richtext box:

private async void rtb_msg_TextChanged(object sender, EventArgs e)
{
    btn_save.Enabled = true;
    rtb_msg.ScrollToCaret();
    rcvFlag = true;
    await SaveFile();
}

Async Save file Method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private async Task SaveFile()
{
    if (_serialPort.BytesToRead == 0 && rcvFlag == true)
    {
        for(int i = 0; i < 10; i++)
        {
            Thread.Sleep(1000);
        }
        using (StreamWriter writer = new StreamWriter(reportFolder + reportFile))
        {
            await writer.WriteAsync(rtb_msg.Text);
        }
        rcvFlag = false;
    }
}

>Solution :

This part will definitely block your UI thread:

for(int i = 0; i < 10; i++)
{
    Thread.Sleep(1000);
}

Not sure why it’s there, but if you replace it with an async version, it should work:

for(int i = 0; i < 10; i++)
{
    await Task.Delay(1000);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading