'Await Task - How to write a text file meantime the progress bar is running?

Scenario : a process write a textfile and in meantime another with the progress bar show current situation. At the end a messagebox show Done

What's wrong ? The code doesn't show the progress situation, and only at the end I can see progress bar at 100% and the Messagebox.

Why this problem ?

This is my code

<Button Command="{Binding MyCommand2}" Content="Click Me" Margin="10,10,670,321"/>
        
<ProgressBar HorizontalAlignment="Left" Height="17" Margin="172,200,0,0" VerticalAlignment="Top" Width="421" Maximum="20" Value="{Binding Prog_bar_value}"/>



public int ncount = 0;

private int _prog_bar_value;
public int Prog_bar_value
{
    get { return _prog_bar_value; }
    set
    {
        _prog_bar_value = value;
        base.OnPropertyChanged("Prog_bar_value");
    }
}



private async void startButton_Click()
{
    await WriteTextFile(); // The 2 methods must be separated.
    await Progress();

    MessageBox.Show("Done");  //here we're on the UI thread.
}


async Task Progress()
{
    await Task.Run(() =>
    {
        Prog_bar_value = ncount;
    });
}


async Task WriteTextFile()
{
    await Task.Run(Exec_WriteTextFile);
}


void Exec_WriteTextFile()
{
    using (StreamWriter sw = File.CreateText(@"C:\temp\Abc.txt"))
    {
        for (int i = 0; i < 20; i++)
        {
            sw.WriteLine("Values {0} Time {1} ", i.ToString(), 
            DateTime.Now.ToString("HH:mm:ss"));
            ncount = i;
            Thread.Sleep(500); //this is only for create a short pause
        }
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source