目前我的代码变得非常重复。我必须在整个软件过程中反复提高忙碌指示器。
这三个 Action 是
1. Raise Busy Indicator
2. Do the actions
3. Turn Off Busy Indicator
例子
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 });
}
我希望运行一种方法,这样它就可以执行繁忙指示器,而不必每次都重复它。
有点像
public async void OpenAttachment()
{
Execute(() => await Task.Run(() => {....TaskWork});
}
想知道是否有人可以给我提示如何减少这些重复代码。
最佳答案
你的意思是这样的?
public async Task RunBusyTask(Action task)
{
Events.PublishOnUIThread(new BusyEvent { IsBusy = true });
await Task.Run(task);
Events.PublishOnUIThread(new BusyEvent { IsBusy = false });
}
RunBusyTask(() => {...});
关于c# - Task.Run() 的回调方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093651/