Search code examples
c#task-parallel-libraryinvoke

Invoke failed in a task


I have this code :

var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
{
    // Code...
    Invoke(new Action(() => progressBar.Increment(1)));
    // Code...
});

task.Wait();

But the Invoke fail, without Exception or any kind of error. It seems that the "wait" prevents the refresh of the form, probably because I'm still in the method.

how do I get around this?

Thanks


Solution

  • You got yourself a dead-lock.

    When the Task is running (on a different thread) and you call Invoke, it wants to invoke it on the mainthread. But the mainthread is waiting for the Task to complete... (task.Wait() will block until it's ready)

    What if you use:

    await task;
    

    The method using this code should be marked as async. The compiler will cut the method into pieces, and while waiting, the messageloop/thread runs again. When the task is ready, the rest of the method will be executed. (below the await task;)


    Look here for more info: await vs Task.Wait - Deadlock?