Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Back Method for Task.Run()

Tags:

c#

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.

like image 317
Master Avatar asked Jul 18 '26 01:07

Master


1 Answers

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(() => {...});
like image 98
IS4 Avatar answered Jul 19 '26 15:07

IS4