Search code examples
c#asp.netwcfweb-serviceswcf-client

Updating Progress when Handling Call backs with WCF


I have a program that accesses a WCF Web Service I have running via HTTP.

The program needs to login and the login process is this:

Get Staff List from WebService. 
Gets Drivers List from Webservice.
Gets Vehcile list from web service.
logged in.

I would like to update the progress after each stage. So I thought I would chain them via the IAsycnhResult methods..

However when I try and update the progress from these handlecallback methods, i get an error:

The calling thread cannot access this object because a different thread owns it.

Code:

ASreference.Service1Client client = new ASreference.Service1Client();

private void login()
{
//User has already entered username/password
AsyncCallback CallBack = new AsyncCallback(HandleCallback);
client.BeginGetStaff(CallBack, client);

TxtboxPassword.IsEnabled = false;
TxtboxUsername.IsEnabled = false;
LblProgress.Content = "Logging In";
progress.Value = 10;
}

void HandleCallback(IAsyncResult result)
{
    bool success = false;

    try
    {
        Staff = client.EndGetStaff(result);                
        success = true;
    }
    catch
    {
        MessageBox.Show("Incorrect username or password");
        client = new ASreference.Service1Client();
        EnableTextbox();
    }

    if (success)
    {
        AsyncCallback CallBack = new AsyncCallback(DriversCallBack);                
        client.BeginGetDrivers(CallBack, client);
        LblProgress.Content = "Downloading Drivers";  //CAUSES ERROR
        progress.Value = 30;
    }

    }

How do you update the progress safely?


Solution

  • progress.Dispatcher.Invoke(
          System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
            delegate()
            {
                    LblProgress.Content = "Downloading Drivers";
                    progress.Value = 30;
            }
        ));