I have a WCF service which implements a ServiceContract. For the sake of simplicity say the ServiceContract has only 1 method:
public interface ServiceContract
{
String AddNewData(T arg1);
}
Here AddNewData can add data to Database1 or Database2 depending on
value of arg1. At certain point in time for a given value of arg1 say val1, we are trying to switch the storage from Database1 to Database2 and this process is time consuming (Say, it takes around a minute). During this period all the calls for arg1 == val1, should be suspended but we should still be able to perform AddNewData for all other values of arg1 i.e. we should not be blocking the main thread.
I was thinking since AddNewData is the entry point for the call, I guess I want to be able to create Task which executes AddNewData but in case of arg1 == val1, I do not execute the Task but keep it suspended (in a not started state) and when the switch from Database1 to Database2 has taken place, I can run/start this suspended Task.
I was thinking in terms of Task as I do not want to block the main thread to perform AddNewData for other values of arg1.
Now I am not sure how do I decide whether I want to start AddNewData or not before even entering the method for a given value of arg1. As per my understanding, I cannot suspend the execution of the AddNewData after entering the method as it would block the main thread. I looked into IDispatchMessageInspector.AfterReceiveRequest but couldn't figure out how to leverage this.
Anyone with any suggestions on how should I go about this. I am new to WCF and multithreading, so please excuse me if I am missing something straight forward here.
Just use an async service contract
[ServiceContract]
public interface IServiceContract<T>
{
[OperationContract]
Task<string> AddNewData(T arg1);
}
then on the 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 from
https://blogs.msdn.microsoft.com/endpoint/2010/11/12/simplified-asynchronous-programming-model-in-wcf-with-asyncawait/
and it contains a full example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With