Arkadiusz
Arkadiusz

Reputation: 51

bind log Asynchronous in winForm c#

I tried to add something to log inside WinForm while doind something

    private async Task SaveChunk(DataChunkSaver chunk)
    {
        int i = 0;
        int step = 10;

        while (chunk.saveChunk(i, step))
        {
            i += step;
            AddLog(chunk.Log);
        }
    }

where:

    private async Task AddLog(string text)
    {
        LogBulider.AppendLine(text);
         LogBox.Text = LogBulider.ToString();
    }

AndLogBulider is a simple global StringBulider. The problem is when I fire button with SaveChunk task my form freezes, so I can see the LogBox after everything is done and I wanned it to bisplayed after each step of chunk.saveChunk.
I tried to fire them by few methods, but I can't handle it

What Am I doing wrong?

        private async void button2_Click(object sender, EventArgs e)
            {
    await Task.Factory.StartNew(() => SaveChunk(chunk));
    Task T = SaveChunk(chunk);
    // none of these works, I also tried few other
//ways to do it, but none prevents my winForm from freezing
        }

Upvotes: 0

Views: 154

Answers (1)

Fildor
Fildor

Reputation: 16059

I tried to modify your code using a Progress<string>:

private async void button2_Click(object sender, EventArgs e)
{
    var progress = new Progress<string>(msg =>
    {
     LogBulider.AppendLine(msg);
     LogBox.Text = LogBulider.ToString();
    });
    await Task.Run(() => SaveChunk(chunk, progress));
}

and

private async Task SaveChunk(DataChunkSaver chunk, IProgress<string> progress)
{
    int i = 0;
    int step = 10;

    while (chunk.saveChunk(i, step))
    {
        i += step;
        progress?.Report(chunk.Log); // Always use progress as if it could be null!
    }
}

Upvotes: 1

Related Questions