I have a third-party API which requires thread affinity. I am using WCF in my service application to handle requests from a client which are then delegated to this API. Since WCF uses a thread pool to handle requests, I attempted to work around this with the following code (using SynchronizationContext class):
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Threading;
namespace MyAPIService
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService: IService
{
ThirdPartyAPI m_api;
SynchronizationContext m_context;
MyService()
{
m_api = new ThirdPartyAPI();
}
public bool Connect(string ipaddress, int port)
{
m_context = (SynchronizationContext.Current == null) ? new SynchronizationContext() : SynchronizationContext.Current;
return m_api.Connect(ipaddress, port);
}
public bool Disconnect()
{
throw new NotImplementedException();
}
public bool IsConnected()
{
return Send(() => m_api.IsConnected());
}
public TResult Send<TResult>(Func<TResult> func)
{
TResult retval = default(TResult);
m_context.Send(new SendOrPostCallback((x) =>
{
retval = func();
})
, null);
return retval;
}
}
}
}
I thought this was would allow me to execute the IsConnected method on the same exact thread that Connect was called on but from testing this is not the case. IsConnected still executes on any thread in the pool. What am I doing wrong?
Any help would be greatly appreciated. Thank you very much.