Hello esteemed colleagues, I need to save to a text file every time I get a new message from my serial port into my RichTextBox
. 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?
TextChanged
event handler from RichTextBox
:
private async void rtb_msg_TextChanged(object sender, EventArgs e)
{
btn_save.Enabled = true;
rtb_msg.ScrollToCaret();
rcvFlag = true;
await SaveFile();
}
Async SaveFile
method:
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;
}
}
CodePudding user response:
Never use Thread.Sleep
in async methods. Use Task.Delay
and Task.Run
instead
private Task SaveFileAsync()
{
return Task.Run(async () =>
{
if (_serialPort.BytesToRead == 0 && rcvFlag == true)
{
for (var i = 0; i < 10; i )
{
await Task.Delay(1000);
}
using (var writer = new StreamWriter(reportFolder reportFile))
{
await writer.WriteAsync(rtb_msg.Text);
}
rcvFlag = false;
}
});
}
CodePudding user response:
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);
}