.Net:CallBack 应该在哪个线程上?
我构建了一个与 JSON 服务对话的帮助程序类。该类在后台线程中完成其工作。完成后,它调用一个 Action<>客户端发送的回调。
最好让辅助类调用 Action<> 吗?主 UI 线程上的回调,还是线程应该由客户端负责?
I have built a helper class that talks to a JSON service. The class does its work in a background thread. When done, it calls an Action<> CallBack which the client sent it.
Is it best to have the helper class call the Action<> callback on the main UI thread, or should threading be the responsibility of the client?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该提供完整的同步 API(如
object Fetch()
)和显式标记的异步 API(如void FetchAsnyc(Callback)
)。也许您的客户使用不同的多任务处理方法,然后他可以使用您的同步 API 来实现这一点。而且 UI Thread 确实不是你的范围。
You should provide a complete synchronous API like
object Fetch()
and an explicitly marked asynchronous API likevoid FetchAsnyc(Callback)
. Maybe your client use a different approach to Multitasking then he can implement this with your synchronous API.And the UI Thread is really not your scope.
我更喜欢有一个能够同时接收和发送数据的异步服务,这也提高了服务的可靠性。这种方法可以避免客户端问题时经常发生的慢消费者问题,因此服务可以安全地免受此类慢/有问题的客户端的影响。
对于UI线程,这是客户端的责任。基本上,客户端负责在 UI 线程上调度操作。
编辑:Skomski 的回答让我想起了我们最近使用的一种方法
基本上服务提供了如下方法:
因此客户端可以选择是否传递自己的同步上下文,以便服务在分派消息时使用它
或以更直接的方式使用它。
I would preffer to have an asynchronous service which able to receive and send data simultaneously, this increases reliability of service as well. This approach allows to avoid Slow Consumer problem which often happens in case of client-side problems, so a service would be safe from such kind of slow/problematic clients.
Regarding UI thread, this is a responsibility of a client. Basically client is responsible to dispatch action on UI thread.
EDIT: Skomski's answer recalled me an approach we've used recently
Basically service provides methods like following:
So client has an option whether pass own synchronization context so service will use it when dispatching messages
or use it in more straightforward way.