I have encountered a problem about injecting new code block to an action delegate.
For instance, i have a method like this:
private void methodAsync(Action action)
{
new Task(action).Start();
}
And i call this method like below:
methodAsync(() =>
{
writeMessage("Task started");
//do some stuff
writeMessage("Task completed");
});
However, i do not want to call methodAsync with lots of writeMessages. Instead of i want to call like below:
methodAsync(() =>
{
//do some stuff
});
Since in every methodAsync call i will definitely put writeMessage, could i inject writeMessage in all of the action delegates in methodAsync like this:
private void methodAsync(Action action)
{
//inject here
new Task(action).Start();
}
Unfortunately, Action delegate has only some methods like invoke, begininvoke, etc that does not solve my issue. And I do not want to write IL Code as you understand
It sounds like you just want:
private void methodAsync(Action action)
{
new Task(() => {
writeMessage("Task started");
action();
writeMessage("Task completed");
}).Start();
}
In other words, you're not changing the action - you're just calling it within another one.
As an alternative, you could use delegate composition:
private void methodAsync(Action action)
{
Action before = () => writeMessage("Task started");
Action after = () => writeMessage("Task completed");
new Task(before + action + after).Start();
}
For the "after" part, another alternative would be to add a continuation to the task. Aside from anything else, that would allow you to log if the task failed, too.
(You should change your methods to follow .NET naming conventions, by the way. You might also want to look at using Task.Run
, and probably returning the task from the method.)
See more on this question at Stackoverflow