Search code examples
c#wpfuser-interfacetaskbusiness-logic

WPF/C# task async for dummies: How to build a simple UI/BL cooperation?


I'm almost completely virgin in threading / backgroundworkers etc.

I am trying to do this:

  1. New window shows status of a process (label) and has an ongoing XAML-defined animation with a storyboard (three points representing a process in the background).
  2. Run some background intensive code, that requires some input and returns no output.
  3. When finished, update the UI with a message
  4. Repeat 2 & 3 tens of times with different operations in the background each time.

While the background BL is operating I'd like the UI not to hang, but the continuation of the execution of the next BL method should only execute after the first one has ended and the UI has been updated with the message I'd like to present.

I'd like the slimmest, simplest way to do this. using .Net 4.5, so I believe we're talking Tasks, right?

I've read dozens of Stackoverflow articles and consulted uncle google and aunt MSDN, but it's overwhelming - there are many ways to do this, and I'm a bit lost.

Thanks in advance.


Solution

  • Whatever you're talking about are fairly simple to do with async/await. Since you said you're new to multithreading, I recommend you to read and make yourself familiarize with it. Here is a good start and this

    I assume you can implement #1 yourself and you only need guidance in implementing rest. So, I'll not be talking about it in my post.

    Theoretically you need a collection with the list of work needs to be done, then start one by one after the previous one is completed.

    To give some code sample

    List<WorkItem> workItems = ...;//Populate it somehow
    
    private async Task DoWorkMain()
    {
        foreach (var item in workItems)
        {
             await DoWork(item);
             //WorkItem completed, Update the UI here,
             //Code here runs in UI thread given that you called the method from UI
        }
    }
    
    private Task DoWork(WorkItem item)
    {
        //Implement your logic non blocking
    }
    

    Then somewhere from the UI call

    await DoWorkMain();
    

    WorkItem is a class which holds data about the work to be done.