Search code examples
wcfwindows-phone-7c#-4.0backgroundworker

WP7 Service Call in background worker C#


I am developing an wp7 app. In that i consume WCF service to get data on application start. After getting data i need to store it in ISO Store. Service call is happened in DoWork event of BackGroundWorker. To my knowledge only async call is possible with WCF in windows phone 7. I am getting data on Completed event of service call. But the Background worker completed event is occurring before Completed event of service. I need to update some online status of user after getting data from service call.

What is the best practice to update my status. Is it good to do in Completed event of service call? or is there any way to update the status in Background worker completed event.

Here is my code

    private void StartLoadingData(bool status)
    {

        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        worker.RunWorkerAsync(status);
    }


    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        if (!string.IsNullOrEmpty(this.CurrentUser))
        {
           ServiceReferenceClient cl = new ServiceReferenceClient() ;
            cl.ChangeUserStatusCompleted += new EventHandler<ChangeUserStatusCompletedEventArgs>(cl_ChangeUserStatusCompleted);
            cl.ChangeUserStatusAsync(this.CurrentUser, true);               
            e.Result = true;
        }           

    }

    private void cl_ChangeUserStatusCompleted(object sender, ChangeUserStatusCompletedEventArgs e)
    {
        // here i will get my result to process next step
    }
   private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
      // result obtained from service need here
    }

Solution

  • Why are you using a backgroundworker for an asynchronous call? If you need it to execute the callback in the UI thread, you can use the dispatcher instead:

    private void StartLoadingData(bool status)
    {
        if (!string.IsNullOrEmpty(this.CurrentUser))
        {
           ServiceReferenceClient cl = new ServiceReferenceClient() ;
           cl.ChangeUserStatusCompleted += new EventHandler<ChangeUserStatusCompletedEventArgs>(cl_ChangeUserStatusCompleted);
           cl.ChangeUserStatusAsync(this.CurrentUser, true);               
        }  
    }
    
    private void cl_ChangeUserStatusCompleted(object sender, ChangeUserStatusCompletedEventArgs e)
    {
        Dispatcher.BeginInvoke(() => 
        {
            // Update the UI here
        });
    }