0
votes

I'm currently developing in WPF / MVVM following the dataservice pattern where ViewModel call a Service that contains all the business objects and method.

Now, when I call the service method, this requires a bit of time so I should create a new Task in order to let the GUI not freezed.

In your opinion, where is the best location to start a task, in the ViewModel or in the Service itself?

...
// TaskFactory.StartNew(() => {}); // where I should put this ? *
...

class DataService
{
    MyBussObj mbo;

    CallBusinessOperation()
    {
        // * here ?
        while (mbo.Next())
        {
            // requires a while
        }
    }
}

class MyViewModel
{
    DataService service = new DataService();

    void DoIt()
    {
        // * here ?
        service.CallBusinessOperation();
    }
}   
2
IMO you should make service methods async, and call them with await - netaholic
because it's more clear and transparent, than simply using tasks - netaholic
if you are in Net 4.0 you can only use Task - Fabrizio Stellato

2 Answers

1
votes

I would create and start the task in the view model.

Theoretically, you could start 3 different tasks in your view model and only update the UI when all or the first of them is finished. In this case, the view model is in charge of the control flow.

If the service method implementation itself has control logic which needs to access several other services async, I would start the respective tasks there.

To summarize, I would start the tasks where the control logic resides.

0
votes

I would do this in the ViewModel because than you can easily refresh your properties on ProgressChanged or anything else you want.