WCF Invoke method only if certain condition is met or waiting
I have a WCF service that implements ServiceContract
. For simplicity, it ServiceContract
is said to have only one method:
public interface ServiceContract
{
String AddNewData(T arg1);
}
Here AddNewData
can add data to Database1
or Database2
depending on the value arg1
. At some point in time for a given value, arg1
let's say val1
we try to switch storage from Database1
to Database2
, and this process takes a long time (let's say it takes about a minute). During this period, all calls for arg1 == val1
must be suspended, but we must still execute AddNewData
for all other values arg1
, that is, we must not block the main thread.
I thought since it AddNewData
is the entry point for the call, I assume I want to be able to create Task
that does AddNewData
, but in case arg1 == val1
I am not executing the task, but keep it paused (in a non-running state) and when the transition from Database1
to occurs Database2
, I can run / start this suspended task. I was thinking in terms of a task as I don't want to block the main thread to execute AddNewData
for other values arg1
.
Now I'm not sure how I should decide if I want to start AddNewData
or not, even before entering a method for a given value arg1
. In my opinion, I cannot pause execution AddNewData
after entering the method as it blocks the main thread. I looked at IDispatchMessageInspector.AfterReceiveRequest but couldn't figure out how to use that.
Anyone with any suggestions as to how I should go about this. I'm new to WCF and multithreading, so please excuse me if I'm missing something right here.
Just use the async service contract
[ServiceContract]
public interface IServiceContract<T>
{
[OperationContract]
Task<string> AddNewData(T arg1);
}
then server side
const int val1 = 10;
public class HelloService<int> : IServiceContract<T>
{
public async Task<string> AddNewData(int arg1)
{
if(arg1==val1){
// Poll to see if the database is ready
// or use some other method that returns a
// a task when it is ready
while(!(await DataBaseReady())
await Task.Delay(TimeSpan.FromSeconds(1));
}
return "Got it"
}
}
The above was shamelessly ripped off
https://blogs.msdn.microsoft.com/endpoint/2010/11/12/simplified-asynchronous-programming-model-in-wcf-with-asyncawait/
and contains a complete example