JDoe
JDoe

Reputation: 75

App freezes then shows everything at once

I'm new to C# and I need some help.

In my application, I would like to display some kind of log message (e.g. "Starting task 1") before several quite long running tasks to show where the script is in the process.

But instead of doing: display log, do the task, display log, do the next task, etc. the application freezes, displays nothing, then once all 'heavy' tasks are done, it displays every log.

I would have thought that it would display a log, then freeze during one task, then show another log, and freeze again for the next task, but instead it freezes right at the beginning of the function.

This is a sample of my code:

public void Work(string src, string spl)
{
    log("=======================");
    string cmd = ...; // some arguments for external exe

    var proc = new System.Diagnostics.Process
    {
        StartInfo = new System.Diagnostics.ProcessStartInfo
        {
            FileName = ..., // some external app
            Arguments = cmd,
            UseShellExecute = false,
            RedirectStandardOutput = false,
            CreateNoWindow = true
        }
    };

    log("Task 1 started. Please wait...");
    proc.Start();
    proc.WaitForExit();
    proc.Close();
    log("Task 1 done.");
}

public void log(string message)
{
    ScrollContent.Text += "\n" + message;
}

Now I'm learning about threads and the Task class, but it doesn't seem to work. I've tried this:

public void Work(string src, string spl)
{

    // same as before

    log("Task 1 started. Please wait...");

    Task.Factory.StartNew(() => StartProc(proc)).Wait;

    log("Task 1 done.");
}

public void StartProc(System.Diagnostics.Process proc)
{
    proc.Start();
    proc.WaitForExit();
    proc.Close();
}

So it can do the heavy task in another thread, but nope, it still freezes at the beginning of the function, until it's done. I'm probably doing something completely wrong, but I don't know what.

Thank you.

Upvotes: 0

Views: 56

Answers (1)

pquest
pquest

Reputation: 3290

When you use Wait like that, you are waiting for the process to end synchronously instead of asynchronously. You should change your Work method to:

public async Task Work(string src, string spl)
{

    // same as before

    log("Task 1 started. Please wait...");

    await Task.Factory.StartNew(() => StartProc(proc));

    log("Task 1 done.");
}

which will block progress asynchronously instead.

Upvotes: 2

Related Questions