在 C# 中,我有一个类层次结构,这些类执行可能需要很长时间的操作。为此,我实现了一种解耦/回调机制,这样调用者就不会被阻塞,而是通过回调接口(interface)得知操作已完成。这看起来像这样:
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# 是否提供了任何可以使此操作变得更容易/更简洁的构造?
最佳答案
asynchronous programming patterns on MSDN 有很好的文档。如果您使用 .NET 4,您应该查看 Task Parallel Library (TPL)。
涵盖了使用委托(delegate)的异步编程 here (还有一个额外的 example )。如果遵循 MSDN 的实践和建议,您可能会做得更糟。
关于c# - 使用 delegate/BeginInvoke 在 C# 中将调用者与被调用者解耦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7889042/