Click here to Skip to main content
15,888,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a regular requirement for returning newly saved record id from database through wcf service.

I have a service which is used to save the record and at the same time the newly inserted record id (say ConsultationID) need to return from the service.

But unfortunately, the asynchronous service initially returns 0, which is the initial value and after the method executes, it returns the actual value. Can anybody tell me how to retrieve the return value from the service synchronoysly.

Code Sample:
public int SaveConsultation()
{
   ConsultationService client=new ConsultationService();

   ConsultationService.Consultation objConsultaiton =      
        ConsultationService.Consultation();

   objConsultaiton.consultaitonName = "xxxxx";

   objConsultaiton.consultaitonAddress = "yyyyyyy";

   client.saveRecordAsync(objConsultaiton);

   client.saveRecordCompleted += (ss,ee)=> {
       objConsultaiton.consultationID = ss.result;
   };

   return objConsultaiton.consultationID;

}

But " return objConsultaiton.consultationID " is executed before client.saveRecordCompleted event and i am getting the cnsultationID as '0'

Please suggest me the solution.
Posted
Updated 2-Dec-09 3:54am
v2

1 solution

There are 2 errors that I could see:

1. The call to method client.saveRecordAsync(objConsultaiton) should be called *after* attaching the client.saveRecordCompleted event handler.
2. Since the consultationID is available only after the Asynchronous call is returned, you need to wait for the Asynchronous call to complete.

The following changed code should work (I have not tested the code):
public int SaveConsultation() 
{   
ConsultationService client=new ConsultationService();   ConsultationService.Consultation objConsultaiton =             ConsultationService.Consultation();   
objConsultaiton.consultaitonName = "xxxxx";   objConsultaiton.consultaitonAddress = "yyyyyyy";  
AutoResetEvent objAutoReset = new AutoResetEvent(false); //flag to track call back
client.saveRecordCompleted += (ss,ee)=> 
{       
    objConsultaiton.consultationID = ss.result;   
    objAutoReset.Set();  //flag confirming call back
};   
client.saveRecordAsync(objConsultaiton);   
objAutoReset.WaitOne(); //Wait till the flag is set by Async Call back
return objConsultaiton.consultationID;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900