[英]Add New Code Block Dynamically To Action Delegate in .Net
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. 但是,我不想使用很多writeMessages来调用methodAsync。 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: 由于在每个methodAsync调用中我都一定会放置writeMessage,因此我可以在methodAsync的所有操作委托中注入writeMessage,如下所示:
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. 不幸的是,动作委托只有一些方法(例如invoke,begininvoke等)无法解决我的问题。 And I do not want to write IL Code as you understand
而且我也不想写IL代码
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.) (顺便说一下,您应该更改方法以遵循.NET命名约定。您可能还想看看使用
Task.Run
,并且可能从该方法返回任务。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.