使用 delegate/BeginInvoke 在 C# 中将调用者与被调用者解耦
在 C# 中,我有一个类层次结构,这些类执行可能需要很长时间的操作。为此,我实现了一种解耦/回调机制,这样调用者就不会被阻塞,而是通过回调接口得知操作已完成。这看起来像这样:
protected delegate void ActionDelegate();
public void doAction()
{
Task.Factory.StartNew(() => DoActionASync());
}
private void DoActionASync()
{
DoActionImpl();
Caller->ActionDone(); // Caller is registered separately, and implements an interface (ICallback) that includes this function
}
protected abstract void DoActionImpl(); // Derived classes implement this
这是相当多的重复代码,每个方法都有微小的差异(签名)。我的问题是,这是否是解决此问题的正确方法,或者 .NET/C# 是否提供了任何可以使此操作变得更容易/不那么冗长的构造?
In C# I have a hierarchy of classes that perform actions that could potentially take a long time. For this reason, I implemented a decoupling/callback mechanism so the caller is not blocked, but is informed of an action's completion through a callback interface. This looks something like this:
protected delegate void ActionDelegate();
public void doAction()
{
Task.Factory.StartNew(() => DoActionASync());
}
private void DoActionASync()
{
DoActionImpl();
Caller->ActionDone(); // Caller is registered separately, and implements an interface (ICallback) that includes this function
}
protected abstract void DoActionImpl(); // Derived classes implement this
This is quite a lot of code that is repeated with minor differences (in signature) for each method. My question is whether this is the right way to approach this, or does .NET/C# offer any constructs that would make this easier/less verbose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MSDN 上有关于异步编程模式的优秀文档。如果您使用的是 .NET 4,则应该查看任务并行库(TPL)。
此处介绍了使用委托的异步编程(还有一个额外的示例)。如果遵循 MSDN 的实践和建议,您可能会做得更糟。
There is good documentation on asynchronous programming patterns on MSDN. If you are using .NET 4, you should look into the Task Parallel Library (TPL).
Asynchronous programming using delegates is covered here (there is also an extra example). You could do much worse that follow MSDN's practices and suggestions.