简体   繁体   English

Task.Run()的回调方法

[英]Call Back Method for Task.Run()

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. 想知道是否有人可以给我如何减少重复代码的提示。

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(() => {...});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM