我的代码调用了一个Web 服务方法,该方法需要几分钟来执行操作。在此期间,我的窗口变得无响应,并显示一个完整的白屏。
我不想从不同的线程调用方法。
这是最好的处理方式吗?
环境:C#,网络服务
BackgroundWorker是你的朋友。
这是我如何将 BackgroundWorker 与 WebService 一起使用的示例。基本上,如果不使用单独的线程,就无法在 UI 端进行密集操作。BackgroundWorker 是在单独线程上运行的最佳方式。
要拥有响应式 UI,您必须使用另一个线程。
但是,如果您使用 Visual Studio,生成的客户端类具有异步方法签名,可以为您完成。如果您的方法是“GetData”,那么您应该有一个名为“GetDataAsync”的方法,它不会冻结您的窗口。
这是一个例子:
WsClient client;
protected override void Load() {
base.Onload();
client = new WsClient();
client.GetDataCompleted += new GetDataCompletedEventHandler(client_GetDataCompleted);
}
//here is the call
protected void Invoke()
{
client.GetDataAsync(txtSearch.Text);
}
//here is the result
void client_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
//display the result
txtResult.Text = e.Result;
}
您可以在单独的线程上发出请求,这将使 UI 线程保持响应。完成后,您需要将响应同步回 UI 线程。