Basically as the question states, if I make my services asynchronous does that mean they aren't interoperable anymore?
As far as the client is concerned, a sync or an async version of the service are identical (see example below). So the sync/async decision does not affect interoperability.
public class StackOverflow_6231864_751090
{
[ServiceContract(Name = "ITest")]
public interface ITest
{
[OperationContract]
string Echo(string text);
[OperationContract]
int Add(int x, int y);
}
[ServiceContract(Name = "ITest")]
public interface ITestAsync
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginEcho(string text, AsyncCallback callback, object state);
string EndEcho(IAsyncResult ar);
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginAdd(int x, int y, AsyncCallback callback, object state);
int EndAdd(IAsyncResult ar);
}
public class Service : ITest
{
public string Echo(string text) { return text; }
public int Add(int x, int y) { return x + y; }
}
public class ServiceAsync : ITestAsync
{
string Echo(string text) { return text; }
int Add(int x, int y) { return x + y; }
public IAsyncResult BeginEcho(string text, AsyncCallback callback, object state)
{
Func<string, string> func = Echo;
return func.BeginInvoke(text, callback, state);
}
public string EndEcho(IAsyncResult ar)
{
Func<string, string> func = (Func<string, string>)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
return func.EndInvoke(ar);
}
public IAsyncResult BeginAdd(int x, int y, AsyncCallback callback, object state)
{
Func<int, int, int> func = Add;
return func.BeginInvoke(x, y, callback, state);
}
public int EndAdd(IAsyncResult ar)
{
Func<int, int, int> func = (Func<int, int, int>)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
return func.EndInvoke(ar);
}
}
public static void Test()
{
foreach (bool useAsync in new bool[] { false, true })
{
Type contractType = useAsync ? typeof(ITestAsync) : typeof(ITest);
Type serviceType = useAsync ? typeof(ServiceAsync) : typeof(Service);
Console.WriteLine("Using {0} service implementation", useAsync ? "Asynchronous" : "Synchronous");
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(serviceType, new Uri(baseAddress));
host.AddServiceEndpoint(contractType, new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
Console.WriteLine("Using the same client for both services...");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.Echo("Hello"));
Console.WriteLine(proxy.Add(3, 4));
((IClientChannel)proxy).Close();
factory.Close();
host.Close();
Console.WriteLine("Done");
Console.WriteLine();
}
}
}
If by "making the service asynchronous", you mean using AsyncPattern, then my understanding is that this has no effect on the client at all, only on how the WCF runtime invokes your operations on the server. The client (a WCF client, that is), as ever, makes its own choice over whether to use asynchronous calls.
From this MSDN page:
To define a contract operation X that is executed asynchronously regardless of how it is called in the client application...
and:
In this case, the asynchronous operation is exposed in metadata in the same form as a synchronous operation: It is exposed as a single operation with a request message and a correlated response message. Client programming models then have a choice. They can represent this pattern as a synchronous operation or as an asynchronous one, so long as when the service is invoked a request-response message exchange takes place.
You're services don't have to do anything "special" ... they still behave the same way. You're clients on the other hand have to consume the services using an Asynchronous Pattern. The easiest way to do this is if you use "Add Service Reference...". Simply check a little box that says "Generate Asynchronous Operations" and voila, you can make asynchronous calls to your service...
Here's a good resource: How to: Call WCF Service Operations Asynchronously
Despite the negative comments, the example at the end is well put. Simply subscribe to the <service-name>Completed event and then make an Async call. The call is made, your UI thread is freed up and as soon as the call completes the event is raised! Be careful with your new found powers!
public class Foo
{
private BarServiceClient client;
public Foo()
{
client = new BarServiceClient();
client.DoWorkCompleted += Client_DoWorkCompleted;
}
private void Client_DoWorkCompleted(object sender, DoWorkCompletedEventArgs e)
{
//e.Result contains your result.
}
public void DoBar()
{
client.DoWorkAsync(); //Called asynchronously, UI thread is free! :)
}
}
Related
The addMessage method asynchronously sends messages to clients.
The problem is that those who send it receive it themselves
That is, the client hears himself
public void AddMessage(byte[] message)
{
IAsyncMessageCallback other = OperationContext.Current.GetCallbackChannel<IAsyncMessageCallback>();
other.BeginOnMessageAdded(message, DateTime.Now, delegate (IAsyncResult ar)
{
other.EndOnMessageAdded(ar);
}, null);
}
I tried to implement it in the following way:
public void AddMessage(byte[] message)
{
lock (subscribers)
{
var connection = OperationContext.Current.GetCallbackChannel<IAsyncMessageCallback>();
string user;
if (!subscribers.TryGetValue(connection, out user))
return;
foreach (var other in subscribers.Keys)
{
//Console.WriteLine(other + " " + connection);
if (other == connection)
continue;
Console.WriteLine(other + " " + connection);
other.BeginOnMessageAdded(message, DateTime.Now, delegate (IAsyncResult ar)
{
other.EndOnMessageAdded(ar);
}, null);
Console.WriteLine(message.Length);
}
}
}
But this leads to terrible brakes
Thank you in advance
The essence of the problem:
1.When more than two users enter, the chat starts to hang (a very long delay appears), and then the connection is broken: The communication object System.ServiceModel.Channels.ServiceChannel cannot be used for communication, since its operation is interrupted
If you remove the foreach loop, there will be no breaks and the chat will work calmly with ten users, but the message will be sent to everyone (that is, I will hear my voice in the chat)
Everything works, but with two users. If more come in then System.ServiceModel.Channels.ServiceChannel cannot be used for communication, since its operation is interrupted
public void SendMessage(byte[] message)
{
var connection = OperationContext.Current.GetCallbackChannel<IChatClient>();
string user;
if (!_users.TryGetValue(connection, out user))
return;
foreach (var other in _users.Keys)
{
if (other == connection)
continue;
other.RecievMessage(user, message);
Console.WriteLine(message.Length);
}
}
If you remove the foreach loop, ten users can come in, but they will hear themselves because the server sends this message to everyone indiscriminately.
if the person who sent the video is the current subscriber they don't send the video to THAT subscriber.
How to implement it?
public class StackOverflow_5979252
{
[ServiceContract(Name = "IMessageCallback")]
public interface IAsyncMessageCallback
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginOnMessageAdded(string msg, DateTime timestamp, AsyncCallback callback, object asyncState);
void EndOnMessageAdded(IAsyncResult result);
}
[ServiceContract(CallbackContract = typeof(IAsyncMessageCallback))]
public interface IMessage
{
[OperationContract]
void AddMessage(string message);
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service : IMessage
{
public void AddMessage(string message)
{
IAsyncMessageCallback callback = OperationContext.Current.GetCallbackChannel<IAsyncMessageCallback>();
callback.BeginOnMessageAdded(message, DateTime.Now, delegate(IAsyncResult ar)
{
callback.EndOnMessageAdded(ar);
}, null);
}
}
class MyClientCallback : IAsyncMessageCallback
{
public IAsyncResult BeginOnMessageAdded(string msg, DateTime timestamp, AsyncCallback callback, object asyncState)
{
Action<string, DateTime> act = (txt, time) => { Console.WriteLine("[{0}] {1}", time, txt); };
return act.BeginInvoke(msg, timestamp, callback, asyncState);
}
public void EndOnMessageAdded(IAsyncResult result)
{
Action<string,DateTime> act = (Action<string,DateTime>)((System.Runtime.Remoting.Messaging.AsyncResult)result).AsyncDelegate;
act.EndInvoke(result);
}
}
static Binding GetBinding()
{
return new NetTcpBinding(SecurityMode.None);
}
public static void Test()
{
string baseAddress = "net.tcp://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(IMessage), GetBinding(), "");
host.Open();
Console.WriteLine("Host opened");
InstanceContext instanceContext = new InstanceContext(new MyClientCallback());
DuplexChannelFactory<IMessage> factory = new DuplexChannelFactory<IMessage>(instanceContext, GetBinding(), new EndpointAddress(baseAddress));
IMessage proxy = factory.CreateChannel();
proxy.AddMessage("Hello world");
Console.Write("Press ENTER to close the host");
Console.ReadLine();
((IClientChannel)proxy).Close();
factory.Close();
host.Close();
}
}
We are going to build a web service from metadata read at runtime. I mean the entire web service: the signatures, contracts and implementation.
There are two main paths I see from here.
The first path is that you generate code. Either you generate C# code in strings and compile it on the fly or more elegantly (and complicatedly), you emit MSIL code. This way you have WCF code and WCF will take care of generating the WSDL from it.
The second path is to use a generic service. A service with an operation Message Process(Message) accepting everything. We still want to expose the service as a 'normal' service, so I would need a WSDL somewhere. How can I create a WSDL? I thought about using System.ServiceModel.Description until I realised that deep inside, this API depends on concrete types. With this approach we wouldn't have any data contract type and would process XML on the fly, using metadata to interpret it. So we need somehow to generate the WSDL. Is that a crazy idea? WSDL has quite a complicated spec...
A third option would be to use an hybrid approach, emitting types just to create signatures but implementing the service using non-emitted code (reflecting on emitted types). Weird, but might be simpler than hand crafting WSDL by hand...
Suggestions?
It's a pain to do, but possible to emitting types. Create your .svc and point it at your custom ServiceHostFactory:
<%# ServiceHost Language="C#" Debug="true" Factory="Foo.FooServiceHostFactory" %>
[ServiceContract]
public class FooService { }
Your ServiceHostFactory is where you generate your operation contracts, types that go with it, etc:
public class FooServiceHostFactory : ServiceHostFactory {
public override System.ServiceModel.ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses) {
ServiceHost serviceHost = new FooServiceHost(baseAddresses);
serviceHost.AddDefaultEndpoints();
GenerateServiceOperations(serviceHost);
return serviceHost;
}
private void GenerateServiceOperations(ServiceHost serviceHost) {
var methodNames = new[] {
new { Name = "Add" },
new { Name = "Subtract" },
new { Name = "Multiply" }
};
foreach (var method in methodNames) {
foreach (var endpoint in serviceHost.Description.Endpoints) {
var contract = endpoint.Contract;
var operationDescription = new OperationDescription("Operation" + method.Name, contract);
var requestMessageDescription = new MessageDescription(string.Format("{0}{1}/Operation{2}", contract.Namespace, contract.Name, method.Name), MessageDirection.Input);
var responseMessageDescription = new MessageDescription(string.Format("{0}{1}/Operation{2}Response", contract.Namespace, contract.Name, method.Name), MessageDirection.Output);
var elements = new List<FooDataItem>();
elements.Add(new FooDataItem { Name = "X", DataType = typeof(int) });
elements.Add(new FooDataItem { Name = "Y", DataType = typeof(int) });
//note: for a complex type it gets more complicated, but the same idea using reflection during invoke()
//object type = TypeFactory.CreateType(method.Name, elements);
//var arrayOfType = Array.CreateInstance(type.GetType(), 0);
//var parameter = new MessagePartDescription(method.Name + "Operation", contract.Namespace);
//parameter.Type = arrayOfType.GetType();
//parameter.Index = 0;
//requestMessageDescription.Body.Parts.Add(parameter);
var retVal = new MessagePartDescription("Result", contract.Namespace);
retVal.Type = typeof(int);
responseMessageDescription.Body.ReturnValue = retVal;
int indexer = 0;
foreach (var element in elements) {
var parameter = new MessagePartDescription(element.Name, contract.Namespace);
parameter.Type = element.DataType;
parameter.Index = indexer++;
requestMessageDescription.Body.Parts.Add(parameter);
}
operationDescription.Messages.Add(requestMessageDescription);
operationDescription.Messages.Add(responseMessageDescription);
operationDescription.Behaviors.Add(new DataContractSerializerOperationBehavior(operationDescription));
operationDescription.Behaviors.Add(new FooOperationImplementation());
contract.Operations.Add(operationDescription);
}
}
}
protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) {
return base.CreateServiceHost(serviceType, baseAddresses);
}
}
In the ServiceHostFactory you define the behaviors along with the metadata, so your behavior would need to implement IOperationBehavior and IOperationInvoker (or you could implement them separately) and look something like this:
public class FooOperationImplementation : IOperationBehavior, IOperationInvoker {
OperationDescription operationDescription;
DispatchOperation dispatchOperation;
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) {
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) {
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) {
this.operationDescription = operationDescription;
this.dispatchOperation = dispatchOperation;
dispatchOperation.Invoker = this;
}
public void Validate(OperationDescription operationDescription) {
}
public object[] AllocateInputs() {
return new object[2];
}
public object Invoke(object instance, object[] inputs, out object[] outputs) {
//this would ALL be dynamic as well depending on how you are creating your service
//for example, you could keep metadata in the database and then look it up, etc
outputs = new object[0];
switch (operationDescription.Name) {
case "OperationAdd":
return (int)inputs[0] + (int)inputs[1];
case "OperationSubtract":
return (int)inputs[0] - (int)inputs[1];
case "OperationMultiply":
return (int)inputs[0] * (int)inputs[1];
default:
throw new NotSupportedException("wtf");
}
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) {
throw new NotImplementedException("Method is not asynchronous.");
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) {
throw new NotImplementedException("Method is not asynchronous.");
}
public bool IsSynchronous {
get { return true; }
}
}
For complex types, this is where you need to make a judgement call, which is the root of your question, is how to emit the types. Here's an example, but you can do it any way you can see fit. I'm calling this in my ServiceHostFactory (warning: it's demo code)
static public class TypeFactory {
static object _lock = new object();
static AssemblyName assemblyName;
static AssemblyBuilder assemblyBuilder;
static ModuleBuilder module;
static TypeFactory() {
lock (_lock) {
assemblyName = new AssemblyName();
assemblyName.Name = "FooBarAssembly";
assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
module = assemblyBuilder.DefineDynamicModule("FooBarModule");
}
}
static public object CreateType(string typeName, List<FooDataItem> elements) {
TypeBuilder typeBuilder = module.DefineType(typeName, TypeAttributes.Public | TypeAttributes.Class);
foreach(var element in elements) {
string propertyName = element.Name;
Type dataType = element.DataType;
FieldBuilder field = typeBuilder.DefineField("_" + propertyName, dataType, FieldAttributes.Private);
PropertyBuilder property =
typeBuilder.DefineProperty(propertyName,
PropertyAttributes.None,
dataType,
new Type[] { dataType });
MethodAttributes GetSetAttr =
MethodAttributes.Public |
MethodAttributes.HideBySig;
MethodBuilder currGetPropMthdBldr =
typeBuilder.DefineMethod("get_value",
GetSetAttr,
dataType,
Type.EmptyTypes);
ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
currGetIL.Emit(OpCodes.Ldarg_0);
currGetIL.Emit(OpCodes.Ldfld, field);
currGetIL.Emit(OpCodes.Ret);
MethodBuilder currSetPropMthdBldr =
typeBuilder.DefineMethod("set_value",
GetSetAttr,
null,
new Type[] { dataType });
ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
currSetIL.Emit(OpCodes.Ldarg_0);
currSetIL.Emit(OpCodes.Ldarg_1);
currSetIL.Emit(OpCodes.Stfld, field);
currSetIL.Emit(OpCodes.Ret);
property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr);
}
Type generetedType = typeBuilder.CreateType();
return Activator.CreateInstance(generetedType);
}
}
update: I wrote a quick example and it is available here.
I have a sample service to test WCF net.tcp communication. It is very simple service and all it does is subscribing a client to the service and then calls callbackchannel to notify all connected clients about broadcasted message. The service is hosted inside IIS 7.5.
Here is service code and test client to test it.
[ServiceContract(CallbackContract = typeof(ISampleServiceCallBack), SessionMode = SessionMode.Required)]
public interface ISampleCuratioService
{
[OperationContract(IsOneWay = true)]
void SubcribeToService(string sub);
[OperationContract]
string GetData(int value);
[OperationContract(IsOneWay = true)]
void Broadcast(string message);
}
public interface ISampleServiceCallBack
{
[OperationContract(IsOneWay = true)]
void NotifyClient(string message);
}
Here is the service implementation:
[ServiceBehavior(Name = "CuratioCSMService", InstanceContextMode = InstanceContextMode.PerSession)]
public class Service1 : ISampleCuratioService
{
private static List<ISampleServiceCallBack> JoinedClien = new List<ISampleServiceCallBack>();
public void SubcribeToService(string sub)
{
var subscriber = OperationContext.Current.GetCallbackChannel<ISampleServiceCallBack>();
if (!JoinedClien.Contains(subscriber))
{
JoinedClien.Add(subscriber);
}
}
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public void Broadcast(string message)
{
JoinedClien.ForEach(c => c.NotifyClient("message was received " + message));
}
}
I can not understand the behavior I get when running it. After the first client runs everything works fine but as I close and open test client app, it throws exception notifying that channel can not be used for communication as it is in fault state.
This is sample test client:
static void Main(string[] args)
{
var callneckclient = new ServiceClientProxy();
var client = new SampleCuratioServiceClient(new InstanceContext(callneckclient));
client.SubcribeToService("me");
Console.ReadLine();
for (int i = 0; i < 15; i++)
{
Console.WriteLine(client.GetData(5));
client.Broadcast("this is from client me");
}
client.Close();
Console.Read();
}
public class ServiceClientProxy : ISampleCuratioServiceCallback, IDisposable
{
public void NotifyClient(string message)
{
Console.WriteLine(message);
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
The situation gets even buggy when I run 5 clients. Non of those send or receive messages.
When a client calls SubcribeToService you add its operation context to a List called JoinedClien.
When you call Broadcast in your server, you call the method NotifyClient on all collected operation contexts for every client that has ever connected.
The problem is, that a disconnected client won't get removed from your JoinedClien list.
When you try to call an operation method on a disconnected operation context, you get the channel is in faulted state error.
To work around, you should subscribe to the Channel_Closed and Channel_Faulted events and also catch the CommunicationException when calling back into your clients and remove the operation context of the faulted clients:
public void Broadcast(string message)
{
// copy list of clients
List<OperationContext> clientsCopy = new List<OperationContext>();
lock(JoinedClien) {
clientsCopy.AddRange(JoinedClien);
}
// send message and collect faulted clients in separate list
List<OperationContext> clientsToRemove = new List<OperationContext>();
foreach (var c in JoinedClien)
{
try {
c.NotifyClient("message was received " + message));
}
catch (CommunicationException ex) {
clientsToRemove.Add(c);
}
}
foreach (var c in clientsToRemove)
{
lock(JoinedClien) {
if(JoinedClien.Contains(c))
JoinedClien.Remove(c);
}
}
}
When adding new clients you have to lock that operation, too:
var subscriber = OperationContext.Current.GetCallbackChannel<ISampleServiceCallBack>();
lock(JoinedClien)
{
if (!JoinedClien.Contains(subscriber))
{
JoinedClien.Add(subscriber);
}
}
How can I force an IMessageInspector to fire only when a specific operation is called, rather than firing whenever a call to the service is made? Currently, I am applying a custom IEndpointBehavior to the endpoint which calls this IMessageInspector, but this is not exactly what I would like to do...
The message inspectors are bound to the dispatch runtime object, which is a single one for each endpoint, not operation. If a parameter inspector works, then you can use it (it's bound to the operation), but if you need a message inspector, then it cannot be bound to a single operation. But you can, inside your inspector, check whether the operation is what you expect (based on the Action header, which is unique per operation), as shown in the code below.
public class StackOverflow_7502134
{
[ServiceContract]
public interface ITest
{
[OperationContract]
string Echo(string text);
[OperationContract]
int Add(int x, int y);
}
public class Service : ITest
{
public string Echo(string text)
{
return text;
}
public int Add(int x, int y)
{
return x + y;
}
}
public class MyInspector : IEndpointBehavior, IDispatchMessageInspector
{
string[] operationNames;
public MyInspector(params string[] operationNames)
{
this.operationNames = operationNames ?? new string[0];
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
public void Validate(ServiceEndpoint endpoint)
{
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
// by default, action == <serviceContractNamespace>/<serviceContractName>/<operationName>
string operationName = request.Headers.Action.Substring(request.Headers.Action.LastIndexOf('/') + 1);
if (this.operationNames.Contains(operationName))
{
Console.WriteLine("Inspecting request to operation {0}", operationName);
Console.WriteLine(request);
Console.WriteLine();
return operationName;
}
else
{
return null;
}
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
string operationName = correlationState as string;
if (operationName != null)
{
Console.WriteLine("Inspecting reply from operation {0}", operationName);
Console.WriteLine(reply);
Console.WriteLine();
}
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
MyInspector inspector = new MyInspector("Add"); // inspecting Add, not Echo
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "").Behaviors.Add(inspector);
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine("Calling Echo");
Console.WriteLine(proxy.Echo("Hello world"));
Console.WriteLine();
Console.WriteLine("Calling Add");
Console.WriteLine(proxy.Add(4, 5));
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
I am trying to make a simple asynchronous call with WCF, but the callback function is never executed. Can anyone tell me what is wrong with the code?
I am using visual studio 2008 with .Net 3.5
Service code
[ServiceContract]
public interface IService1
{
[OperationContract(AsyncPattern = true) ]
IAsyncResult BeginGetData(string value, AsyncCallback callback, object state);
string EndGetData(IAsyncResult result);
}
public class Service1 : IService1
{
#region IService1 Members
public IAsyncResult BeginGetData(string value, AsyncCallback callback, object state)
{
return new CompletedAsyncResult<string>(value, state);
}
public string EndGetData(IAsyncResult r)
{
CompletedAsyncResult<string> result = r as CompletedAsyncResult<string>;
return result.Data;
}
#endregion
}
Client side code
class Program
{
static void Main(string[] args)
{
Service1Client client = new Service1Client();
Console.WriteLine("Start async call");
IAsyncResult result = client.BeginGetData("abc", callback, null);
Console.ReadLine();
}
static void callback(IAsyncResult result)
{
string a = "in callback";
Console.WriteLine(a);
}
}
You need call callback explicitly.
IAsyncResult result = client.BeginGetData("abc", callback, null);
callback(result);
Console.ReadLine();
see reference here.
http://blogs.msdn.com/mjm/archive/2005/05/04/414793.aspx