in the code below what i am trying to do is allow my client to call a wcf method on the server , return success and then give callbacks on the current progress i.e percentage complete. The client can disconnect say after 10% and the method will continue.
On the code below though - the return "success" line causes the function to exit. The reason i want the return is so the client blocks until he knows the service has some important processing complete.
Is this possible?
namespace WCFService
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class WCFJobsLibrary : IWCFJobsLibrary
{
public String ChatToServer(string texttoServer) // send some text to the server
{
Logging.Write_To_Log_File("Entry", MethodBase.GetCurrentMethod().Name, "", "", "", 1);
try
{
// Some extemely important prechecks .....
//........
return "success";
// Dont care now if client disconnects but lets give them some updates as progress happens if they are still connected
IMyContractCallBack callback = OperationContext.Current.GetCallbackChannel<IMyContractCallBack>();
// Some processing .....
callbackmethod("20% complete", callback);
// Some processing .....
callbackmethod("40% complete", callback);
// Some processing .....
callbackmethod("60% complete", callback);
// Some processing .....
callbackmethod("80% complete", callback);
// Some processing .....
callbackmethod("100% complete", callback);
}
catch (Exception ex)
{
return "error";
}
}
public void callbackmethod(string text, IMyContractCallBack somecallback)
{
try
{
somecallback.callbacktoServer(text);
}
catch (Exception)
{
}
}
}
}
You can make the callbacks Async and they will fire, and the method will return, but you have to place the return
line after the callbacks are invoked.
In case of error, WCF has automatic exception handling built in, so you can just Throw
the Exception, you don't need to return it... it can then be caught at the client. And will have more information than just "error".
Example using TPL: (using System.Threading.Tasks
namespace, .net 4+)
string yourMethod()
{
// Logging
try
{
// prechecks
}
catch (Exception ex)
{
return "failed" // ok as you have now if no more information is needed
// throw; // Can also throw exception which WCF client on other end can catch
}
Task.Factory.StartNew(() => {
IMyContractCallBack callback = OperationContext.Current.GetCallbackChannel<IMyContractCallBack>();
// Some processing .....
callbackmethod("20% complete", callback);
// Some processing .....
callbackmethod("40% complete", callback);
// Some processing .....
callbackmethod("60% complete", callback);
// Some processing .....
callbackmethod("80% complete", callback);
// Some processing .....
callbackmethod("100% complete", callback);
});
return "success";
}