使用WCF处理回叫时更新进度

时间:2012-06-10 08:34:16

标签: c# asp.net wcf web-services wcf-client

我有一个程序可以访问我通过HTTP运行的WCF Web服务。

程序需要登录,登录过程如下:

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

我想在每个阶段后更新进度。所以我想我会通过IAsycnhResult方法链接它们。

但是当我尝试从这些handlecallback方法更新进度时,我收到一个错误:

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

代码:

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;
    }

    }

如何安全地更新进度?

1 个答案:

答案 0 :(得分:0)

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