使用 delegate/BeginInvoke 在 C# 中将调用者与被调用者解耦

发布于 2024-12-11 23:00:01 字数 593 浏览 0 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稚然 2024-12-18 23:00:01

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文