简体   繁体   中英

C# waiting task without blocking UI

Let's start with code:

private void StartStopService()
{
    var task = Task.Run(() => debugService.Iterate());
    StartStopInit(true);

    //task.Wait();
    if (task.IsCompleted)
        StartStopInit(false);
}

I am trying to make a program which will execute list of given DLL's from DB one by one without blocking the UI thread in the meantime. Method provided is ran on button click and it is starting a task to iterate over DLL's.

public void Iterate()
{
    foreach (var plugin in runningPlugins)
        ExecutePlugin(plugin);
}

Execute method just executes DLL's one by one.

I need a solution to run StartStopInit() method after all DLL's finished with execution. If I put task.Wait() I will block UI...situation as it is now doesn't of course work because if condition gets passed when task starts. If I implement some kind of endless loop to listen for changes, I will again block the UI. How can I solve this one?

If you can, you should move to the new async/await keywords and surrounding support.

For the particular code in your question, here's what I would do:

  1. Mark the method as async Task to make it clear to calling code that this method is async
  2. Use await on the task inside the method to halt execution and "wait" for the task to complete before continuing

Specifically, this is what it would look like:

private async Task StartStopService()
{
    StartStopInit(true);
    await Task.Run(debugService.Iterate);
    StartStopInit(false);
}

Timing-wise I would signal to surrounding code that the method is now executing before spawning sub-tasks.

Also consider adding try/catch blocks, what would happen if the sub-task throws an exception?

private async Task StartStopService()
{
    try
    {
        StartStopInit(true);
        await Task.Run(debugService.Iterate);
    }
    catch (InvalidOperationException ex)
    {
        // What to do here???
    }
    finally
    {
        StartStopInit(false);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM