I'm trying to make a WritingAnimator but it freezes the UI when I run it... Here is what I did :
public partial class Tsia : Form
{
[...]
private void TypeText()
{
WritingAnimator("Some text");
WritingAnimator("This is another text");
}
private void WritingAnimator(string text)
{
foreach (char c in text)
{
TextBox1.AppendText(c.ToString());
Thread.Sleep(100);
}
}
}
So I searched on Google and I found a way to avoid freezing the UI by using other threads :
public partial class Tsia : Form
{
[...]
private void TypeText()
{
WritingAnimator("Some text");
WritingAnimator("This is another text");
}
private async void WritingAnimator(string text)
{
foreach (char c in text)
{
TextBox1.AppendText(c.ToString());
await Task.Delay(100);
}
}
}
But it types something like a mix of "Some text" and "This is another text" beacause WritingAnimator("This is another text"); don't wait for the end of WritingAnimator("Some text"); ...
How could I fix it ?
public partial class Tsia : Form
{
[...]
private async Task TypeText()
{
await WritingAnimator("Some text");
await WritingAnimator("This is another text");
}
private async Task WritingAnimator(string text)
{
foreach (char c in text)
{
TextBox1.AppendText(c.ToString());
await Task.Delay(100);
}
}
}
"So I searched on Google and I found a way to avoid freezing the UI by using other threads"
await
/ async
is a C# language feature since version 5 and Task.Delay
is a method which is part of the Task Parallel Library (TPL) . The whole TPL + async/await features simplify the usage of asynchrony for developers.
Two more thoughts:
CancellationToken
in case the user wants to stop the animation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.