问题
This might be a very naive question:
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).
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.
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?
回答1:
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.
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.
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".
For an implementation example, see the ActionDispatcherSynchronizationContext within the Nito Asynchronous Library.
来源:https://stackoverflow.com/questions/19307824/c-sharp-threading-calling-a-function-on-a-different-thread-in-its-context-and-r