WCF Service with callbacks coming from background thread?
Posted
by Mark Struzinski
on Stack Overflow
See other posts from Stack Overflow
or by Mark Struzinski
Published on 2010-04-08T20:16:39Z
Indexed on
2010/04/09
13:53 UTC
Read the original article
Hit count: 288
Here is my situation. I have written a WCF service which calls into one of our vendor's code bases to perform operations, such as Login, Logout, etc. A requirement of this operation is that we have a background thread to receive events as a result of that action. For example, the Login action is sent on the main thread. Then, several events are received back from the vendor service as a result of the login. There can be 1, 2, or several events received. The background thread, which runs on a timer, receives these events and fires an event in the wcf service to notify that a new event has arrived.
I have implemented the WCF service in Duplex mode, and planned to use callbacks to notify the UI that events have arrived. Here is my question: How do I send new events from the background thread to the thread which is executing the service?
Right now, when I call OperationContext.Current.GetCallbackChannel<IMyCallback>()
, the OperationContext is null. Is there a standard pattern to get around this?
I am using PerSession as my SessionMode on the ServiceContract.
UPDATE: I thought I'd make my exact scenario clearer by demonstrating how I'm receiving events from the vendor code. My library receives each event, determines what the event is, and fires off an event for that particular occurrence.
I have another project which is a class library specifically for connecting to the vendor service. I'll post the entire implementation of the service to give a clearer picture:
[ServiceBehavior(
InstanceContextMode = InstanceContextMode.PerSession
)]
public class VendorServer:IVendorServer
{
private IVendorService _vendorService; // This is the reference to my class library
public VendorServer()
{
_vendorServer = new VendorServer();
_vendorServer.AgentManager.AgentLoggedIn += AgentManager_AgentLoggedIn; // This is the eventhandler for the event which arrives from a background thread
}
public void Login(string userName, string password, string stationId)
{
_vendorService.Login(userName, password, stationId); // This is a direct call from the main thread to the vendor service to log in
}
private void AgentManager_AgentLoggedIn(object sender, EventArgs e)
{
var agentEvent = new AgentEvent
{
AgentEventType = AgentEventType.Login,
EventArgs = e
};
}
}
The AgentEvent object contains the callback as one of its properties, and I was thinking I'd perform the callback like this:
agentEvent.Callback = OperationContext.Current.GetCallbackChannel<ICallback>();
How would I pass the OperationContext.Current instance from the main thread into the background thread?
© Stack Overflow or respective owner