Home > Blockchain >  .NET 4.7.2 => c-sharp => UI async/await
.NET 4.7.2 => c-sharp => UI async/await

Time:12-07

I'm trying to load a content of a text file into text box asynchronously. Therefore my goal is to not block the UI-Thread. To check that, the code gives feedback with Console.Writeline("..." Thread.CurrentThread.ManagedThreadId)

My first intention shows the code below, which will give me Thread 1 in both Console.WriteLines(). That means UI-Thread is blocked, right?


    private async void cmdProgrammLaden_Click(object sender, EventArgs e)
    {
        Console.WriteLine("Button-Thread-ID: "   Thread.CurrentThread.ManagedThreadId);
        this.txtSendData.Text = await DncProgrammLadenAsync();
    }

    async Task<string> DncProgrammLadenAsync()
    {
        string path     = String.Empty;
        string content  = String.Empty;

        using (OpenFileDialog openFileDialog = new OpenFileDialog())
        {
            openFileDialog.InitialDirectory = @"c:\Test\";
            openFileDialog.Filter           = "Textfile (*.txt)|*.txt";
            openFileDialog.FilterIndex      = 0;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                path = openFileDialog.FileName;
                var filestream = openFileDialog.OpenFile();

                using (StreamReader reader = new StreamReader(filestream))
                {
                    content = await reader.ReadToEndAsync();
                    Console.WriteLine("Task-Thread-ID: "   Thread.CurrentThread.ManagedThreadId);
                    //Thread.Sleep(3000);
                }
            }
            return content;

        }

    }



Then I tried to rework this code like *(short version)*

          Task.Run(() =>
            {
                string content = String.Empty;

                using (StreamReader reader = new StreamReader(@"c:\Test\File C.txt"))
                {
                    content = reader.ReadToEnd();
                    Console.WriteLine("Task-Thread-ID: "   Thread.CurrentThread.ManagedThreadId);
                }
                
            }); 

Then I get different Thread IDs.
But this seems not right to me.

What do I not understand correctly?

CodePudding user response:

That means UI-Thread is blocked, right?

No. By default, await captures the current context and resumes executing the async method in that context when that await completes. The UI thread is not blocked during the await, but the code resumes executing on the UI thread after the await.

However, file streams are tricky. They are only asynchronous if opened with an asynchronous flag, and I have no idea if OpenFile passes that flag. Asynchronous APIs called on a synchronous file handle just run the operation on a thread pool thread (I think).

  • Related