Caliburn-Micro / Caliburn.Micro

A small, yet powerful framework, designed for building applications across all XAML platforms. Its strong support for MV* patterns will enable you to build your solution quickly, without the need to sacrifice code quality or testability.
http://caliburnmicro.com/
MIT License
2.8k stars 778 forks source link

Properly using HandleTask #751

Closed codinghavok closed 2 years ago

codinghavok commented 3 years ago

Hello, I'm upgrading from 3.2 to 4.0. I like to display progress messages in my applications ShellViewModel when changing to my apps "profile screen". Since 4.0 is a little different now being async, do I still need to keep the body of my HandleTasks the same if I'm only upgrading to the new signature and want to keep functionality the same? I have included my loading message method below.

If this is incorrect use , can you please provide an example of how it should be done. Thanks.

public async System.Threading.Tasks.Task HandleAsync(LoadProfileMessage message, System.Threading.CancellationToken cancellationToken)
        {           
            await System.Threading.Tasks.Task.Run(() =>
            {
                BusyMessage = "Loading Profile...";

                IsBusy = true;

                var viewModel = Items.OfType<ProfileViewModel>().FirstOrDefault();

                viewModel.Init(message.ProfileId);

                ProfileViewModel = viewModel;

                ActivateItemAsync(viewModel);

                IsBusy = false;                
            });
            await System.Threading.Tasks.Task.CompletedTask;
        }
vb2ae commented 3 years ago

Your method will work. I think it would be a better practice to load the profile async so you could do something like this. The LoadProfileAsync method is Task so it would not return when the first await completes.

   public async System.Threading.Tasks.Task HandleAsync(LoadProfileMessage message, System.Threading.CancellationToken cancellationToken)
    {
        BusyMessage = "Loading Profile...";
        IsBusy = true;
        await LoadProfileAsync(message);
    }

    private async Task<bool> LoadProfileAsync(LoadProfileMessage message)
    {
        var viewModel = Items.OfType<ProfileViewModel>().FirstOrDefault();
        await viewModel.InitAsync(message.ProfileId);
        ProfileViewModel = viewModel;
        ActivateItemAsync(viewModel);
        IsBusy = false;
        return true;
    }

I am assuming you would create a viewModel.InitAsync method to load the profile.