Centralize before and after actions around a new task created by TPL
-
06-06-2021 - |
質問
In our application ,we use TPL to create tasks whenever we would want to make a service call.We have a busy indicator which is set to true whenever a task is started and cleared whenever the task is completed or faulted.Is there any way to accomplish this in a generic way instead of doing this for every single task created ?
First instance :
ComponentViewModel.Instance.IsApplicationBusy = true;
ComponentViewModel.Instance.BusyMessage = "Loading...";
var task1 = Task.Factory.StartNew(() => DoTask1());
task1.ContinueWith(antecdent =>
{
ComponentViewModel.Instance.IsApplicationBusy = false;
CustomAction1();
}
Second Instance :
ComponentViewModel.Instance.IsApplicationBusy = true;
ComponentViewModel.Instance.BusyMessage = "Loading...";
var task2 = Task.Factory.StartNew(() => DoTask2());
task2.ContinueWith(antecdent =>
{
ComponentViewModel.Instance.IsApplicationBusy = false;
CustomAction2();
}
the same is logic is repeated all through the application whenever a service call is made is there any way to avoid this repetition ?
For example there is a dragstarted and dragcompleted events which get fired for all drag operations , so it possible to have taskstarted and taskcompleted event possibly by extending the task factory or otherwise ?
Edit : Made changes so that the question is more clear.You can now observe that steps before starting and ending a task is same but different functions needs to be executed for each task when it runs to completion
解決
EDIT: It appears I've misunderstood the question. Creating this "start, wait, continue" as a centralized function is a good move, and could be created like this:
public void DoIt(Action ThingToDo) {
ComponentViewModel.Instance.IsApplicationBusy = true;
ComponentViewModel.Instance.BusyMessage = "Loading...";
var loadProviderTask = Task.Factory.StartNew(ThingToDo);
loadProviderTask.ContinueWith(antecdent =>
{
ComponentViewModel.Instance.IsApplicationBusy = false;
}
}