Call async method with vs without await syntax

Haale Hao 1 Reputation point
2022-12-15T09:59:20.983+00:00

use the .Net Framework 4.6.1 , this is my test code:

public async Task<int> Test3()
{
int fatalRet = 0;
await Task.Delay(2000);
DialogResult dret = DialogResult.None;
dret = MessageBox.Show("Test5Dialog", "test" + Thread.CurrentThread.ManagedThreadId.ToString(), MessageBoxButtons.YesNoCancel);
if (dret == DialogResult.Yes)
{
fatalRet = 1;
}
else if (dret == DialogResult.No)
{
fatalRet = 2;
}
else
{
fatalRet = 3;
}
return fatalRet;
}

private async void button5_Click(object sender, EventArgs e)
{
Test3();
for (int i = 0; i < 100000; i++)
{
textBox1.Text = "MainThread:" + i.ToString() + "===" + Thread.CurrentThread.ManagedThreadId.ToString();
await Task.Delay(1000);
}
}

when I click the button5,the button5_click method is called.
After 2 second,the MessageBox pop and the code in Bold style above is still running, textBox1.text content continusly update while the the MessageBox pop.
I watch the ThreadId, it's always the same thread with Id 1.
When a model dialog show, the UI thread is blocked,so who(which thread) do update the textBox1.text???

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-12-16T09:27:54.717+00:00

    Hi @HaaleHao-6958 ,Welcome to A&A,

    When the button is clicked, the button5_Click method is called on the UI thread.

    This method then starts executing the Test3 method asynchronously, delaying for 2 seconds before displaying the message box.

    When the message box is displayed, the UI thread is indeed blocked, which means that the code behind the message box will not execute until the message box is closed.

    However, the textBox1.Text property is being updated in a loop before the message box is displayed, so the loop continues to execute on the UI thread while the message box is displayed.

    As the code shows, it executes on thread 1.

    Best Regards,
    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.