C# 线程:在其上下文中的不同线程上调用函数并返回结果 [英] C# threading: calling a function on a different thread in its context and returning results
问题描述
这可能是一个非常幼稚的问题:
This might be a very naive question:
我正在尝试创建一个使用 ZeroMQ 与多个服务器进行通信的客户端应用程序.客户端希望向这些服务器发送大量请求并获得对它们的响应(因此 req-rep 模式).
I'm trying to create a client application that uses ZeroMQ for communicating to multiple servers. The client would like to send a large number of requests to these servers and get responses to them (so req-rep pattern).
我面临的问题是 ZeroMQ 套接字应该只在它们创建的线程中使用.
The issue I'm facing is that ZeroMQ sockets should only be used in the threads they are created on.
一种方法是在新任务中调用每个请求:在任务内部,创建连接,发送请求并获得响应.但是,连接设置非常昂贵.
One way is to invoke each of the requests in a new task: inside the task, create a connection, send request and get response. However, the connection setup is very expensive.
第二种方法可能是在不同线程中打开与服务器的连接;然后以某种方式在与线程相同的上下文中调用发送例程并获得结果.C#中有没有办法从线程Y调用线程X上的函数,但是在线程X的上下文中执行然后得到返回值?
A second way might be to have the connection open to servers in different threads; then somehow invoke the sending routine in the same context as the thread and get results. Is there a way in C# to call a function on thread X from thread Y, but execute it in the context of thread X and then get a return value?
我知道这可能是一个糟糕的方法.在没有太多开销的情况下实现我想要的最佳方法是什么?
I understand this might be a bad approach. What is the best way to achieve what I want without much overhead?
推荐答案
处理此类场景的典型方法是设置一个 SynchronizationContext.尽管最常见的示例都围绕 UI 线程展开,但该课程正是针对这种类型的场景.
The typical means of handling this type of scenario is to setup a SynchronizationContext. This class is intended for exactly that type of scenario, though the most common examples revolve around the UI thread.
您可以使用SynchronizationContext.Post
异步向该上下文(线程)发送消息",该上下文(线程)将在完成后接收回调.这可以通过 TPL 简化,它特别允许您从 SynchronizationContext
创建一个 TaskScheduler
,这反过来又允许您安排 Task
> 在自定义上下文中运行.
You can use SynchronizationContext.Post
to asynchronously post a "message" to that context (thread) which will receive a callback upon completion. This can be simplified with the TPL, which specifically allows you to create a TaskScheduler
from a SynchronizationContext
, which in turn will allow you to schedule a Task
to run on a custom context.
使用 C# 5,这变得非常有用,因为您可以使用 async
/await
来同步您的调用并将工作推送到/从这些线程".
With C# 5, this becomes incredibly useful, as you can then use async
/await
to synchronize your calls and push work to/from these "threads".
有关实现示例,请参阅ActionDispatcherSynchronizationContext
在 Nito 异步库中.
For an implementation example, see the ActionDispatcherSynchronizationContext
within the Nito Asynchronous Library.
这篇关于C# 线程:在其上下文中的不同线程上调用函数并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!