Home > Software design >  Await Task - How to write a text file meantime the progress bar is running?
Await Task - How to write a text file meantime the progress bar is running?

Time:02-20

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
        }
    }
}

CodePudding user response:

Well with

await WriteTextFile();

you wait until that method (ok, in real the returned Task) is completed. After that completion you set the progressbar value.

You can handle that with IProgress<T>/Progress<T>.

private async void startButton_Click()
{
    var progress = new Progress<int>(value => Prog_bar_value = value);
    await WriteTextFile(progress); 

    MessageBox.Show("Done"); 
}

Task WriteTextFile(IProgress<int> progress)
{
    return Task.Run(() => Exec_WriteTextFile(progress));
}

void Exec_WriteTextFile(IProgress<int> progress)
{
    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"));
            progress.Report(i);
            Thread.Sleep(500); //this is only for create a short pause
        }
    }
}
  • Related