3

at the moment my code is getting very repetitive. I have to raise my busy indicator repeatedly throughout the software.

The three actions are

1. Raise Busy Indicator
2. Do the actions
3. Turn Off Busy Indicator

Example

public async void OpenAttachment()
{
    Events.PublishOnUIThread(new BusyEvent { IsBusy = true });
    await Task.Run(() =>
    {
        try
        {
            if (SelectedAttachment == null)
            {
                return;
            }

            var tempFile = string.Format(
                "{0}\\{1}.{2}", Path.GetTempPath(), SelectedAttachment.FileName, SelectedAttachment.FileExtension);

            System.IO.File.WriteAllBytes(tempFile, UnitOfWork.FileRepository.GetFileBytes(SelectedAttachment.Id));

            Process.Start(tempFile);
        }
        catch (Exception ex)
        {
            Notification.Error("Person - Opening attachment", "File couldn't open, please close last file instance.");
        }
    });
    Events.PublishOnUIThread(new BusyEvent { IsBusy = false });
}

I'm looking to run a method such that it'll execute the busy indicator without having to repeat it everytime.

Something like

public async void OpenAttachment()
{
    Execute(() => await Task.Run(() => {....TaskWork});
}

Wondering if someone can give me tips on how to reduce this repeated code.

4
  • 1
    C# use delegators for it... take a look to the docu... Commented Jan 29, 2016 at 20:42
  • If you need just callback, then you can use good old ContinueWith(). Commented Jan 29, 2016 at 20:46
  • 1
    Do not use async void, it is only allowed to be used to make your method signature compatible with a event handler. Your function does not appear to be a event handler so it should be doing async Task instead. Commented Jan 29, 2016 at 20:49
  • It is an event handler, I'm using Caliburn Micro and it makes things alot easier. @ScottChamberlain
    – Master
    Commented Jan 29, 2016 at 20:52

1 Answer 1

8

You mean something like this?

public async Task RunBusyTask(Action task)
{
    Events.PublishOnUIThread(new BusyEvent { IsBusy = true });
    await Task.Run(task);
    Events.PublishOnUIThread(new BusyEvent { IsBusy = false });
}

RunBusyTask(() => {...});
3
  • 1
    I would make it a async Task not a asnyc void so you could do await RunBusyTask(() => {...});. Asnyc void should only be used to make your method signature be compatible with a event handler. Commented Jan 29, 2016 at 20:48
  • @ScottChamberlain Good point, it's usually better to return Task, unless you need the method for an event.
    – IS4
    Commented Jan 29, 2016 at 20:49
  • 1
    You should really just accept a Task, or a Func<Task>, because the task may not represent CPU bound work.
    – Servy
    Commented Jan 29, 2016 at 21:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.