简体   繁体   English

来自WPF的异步Web服务请求

[英]Async Web Service Requests from WPF

I have tried (and failed) to make asynchronous web service calls from a WPF application. 我尝试过(但失败了)从WPF应用程序进行异步Web服务调用。

I implemented a BackgroundWorker in my code which should do the work, when you press the "Send" button on my GUI. 当您在GUI上按“发送”按钮时,我在我的代码中实现了应该执行该工作的BackgroundWorker It does what it's supposed to, some of the time , but ultimately it doesn't actually run asynchronous. 有时会执行预期的操作 ,但最终实际上并没有异步运行。

When you press the button in my GUI the following code fires: 当您在我的GUI中按下按钮时,将触发以下代码:

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    sQuantity = boxQuantity.Text;
    progressBar.Maximum = double.Parse(sQuantity);
    worker.RunWorkerAsync();
}

sQuantity is just a box with a number in it. sQuantity只是一个带有数字的盒子。 It will determine how many requests you sent to the web service at once. 它将确定您一次发送到Web服务的请求数量。

progressBar is what you would expect: A progress bar. progressBar是您所期望的:进度条。

worker.RunWorkerAsync() is where I call the DoWork method. worker.RunWorkerAsync()是我调用DoWork方法的地方。 It looks like this: 看起来像这样:

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    EnableButton(false);
    List<LoanRequestNoCreditScoreDTO> dtoList = GetData();
    foreach (LoanRequestNoCreditScoreDTO dto in dtoList)
    {
        using (LoanBrokerWS.LoanBrokerWSClient client = new LoanBrokerWS.LoanBrokerWSClient())
        {
            try
            {
                Task<LoanQuoteDTO> lq = RequestQuote(dto, client);
                LoanQuoteDTO response = lq.Result;
                lq.Dispose();
                String responseMsg = response.SSN + "\n" + response.interestRate + "\n" + response.BankName + "\n------\n";
                AppendText(responseMsg);
                worker_ProgressChanged();
            }
            catch (Exception ex)
            {
                AppendText(ex.Message + "\n" + ex.InnerException.Message + "\n");
                worker_ProgressChanged();
            }
        }
    }
    EnableButton(true);
}

Ultimately, this is where I screw up of course. 最终,这是我理所当然的地方。 I want the application to send as many requests as the user specified. 我希望应用程序发送与用户指定数量一样多的请求。 So if I wrote 10 in quantity, I would send 10 requests. 因此,如果我写了10封,我将发送10封请求。 The RequestQuote() method calls the following code: RequestQuote()方法调用以下代码:

private async Task<LoanQuoteDTO> RequestQuote(LoanRequestNoCreditScoreDTO dto, LoanBrokerWS.LoanBrokerWSClient client)
{
    LoanQuoteDTO response = await client.GetLoanQuoteAsync(dto.SSN, dto.LoanAmount, dto.LoanDuration);
    return response;
}

How would I make the DoWork method actually send requests asynchronous? 如何使DoWork方法实际发送请求异步?

The code as-is is asynchronous with respect to the UI thread; 就UI线程而言,代码原样是异步的; what you're asking about it concurrency . 您要问的并发性是什么。 Any kind of complex I/O work is best done with async / await , so I'm going to throw out your background worker and just use straight async . 最好使用async / await完成任何类型的复杂I / O工作,因此我将淘汰您的后台工作人员,仅使用直接async

First, the button handler will handle its own enabling/disabling and executing the main download: 首先,按钮处理程序将处理其自己的启用/禁用和执行主要下载:

private async void btnSend_Click(object sender, RoutedEventArgs e)
{
  var quantity = int.Parse(boxQuantity.Text);
  btnSend.Enabled = false;
  await DownloadAsync(quantity);
  btnSend.Enabled = true;
}

The main download will create a rate-limiting SemaphoreSlim (a common type used to throttle concurrent asynchronous operations), and wait for all the individual downloads to complete: 主要下载将创建一个限速SemaphoreSlim (一种用于限制并发异步操作的通用类型),并等待所有单独下载完成:

private async Task DownloadAsync(int quantity)
{
  var semaphore = new SemaphoreSlim(quantity);
  var tasks = GetData().Select(dto => DownloadAsync(dto, semaphore));
  await Task.WhenAll(tasks);
}

The individual downloads will each first rate-limit themselves, and then do the actual download: 单独的下载将各自先限制自己的速率,然后再进行实际的下载:

private async Task DownloadAsync(LoanRequestNoCreditScoreDTO dto, SemaphoreSlim semaphore)
{
  await semaphore.WaitAsync();
  try
  {
    using (LoanBrokerWS.LoanBrokerWSClient client = new LoanBrokerWS.LoanBrokerWSClient())
    {
      var response = await RequestQuoteAsync(dto, client);
    }        
  }
  finally
  {
    semaphore.Release();
  }
}

For doing progress reports, I'd recommend using the types intended for that pattern ( IProgress<T> / Progress<T> ). 对于执行进度报告,我建议使用用于该模式的类型( IProgress<T> / Progress<T> )。 First, you decide what data you want in your progress report; 首先,您决定要在进度报告中使用哪些数据; in this case, it could just be a string. 在这种情况下,它可能只是一个字符串。 Then, you create your progress handler: 然后,创建进度处理程序:

private async void btnSend_Click(object sender, RoutedEventArgs e)
{
  var quantity = int.Parse(boxQuantity.Text);
  var progress = new Progress<string>(update =>
  {
    AppendText(update);
    progressBar.Value = progressBar.Value + 1;
  });
  progressBar.Maximum = ...; // not "quantity"
  btnSend.Enabled = false;
  await DownloadAsync(quantity, progress);
  btnSend.Enabled = true;
}

(Note that progressBar.Maximum = double.Parse(sQuantity); in the original code was wrong; you should set it to the total number of downloads). (请注意,原始代码中的progressBar.Maximum = double.Parse(sQuantity);是错误的;您应将其设置为下载总数 )。

Then the IProgress<string> just gets passed down: 然后IProgress<string>刚被传递:

private async Task DownloadAsync(int quantity, IProgress<string> progress)
{
  var semaphore = new SemaphoreSlim(quantity);
  var tasks = GetData().Select(dto => DownloadAsync(dto, semaphore, progress));
  await Task.WhenAll(tasks);
}

And when you have progress to report, you use that instance: 当您有进度报告时,可以使用该实例:

private async Task DownloadAsync(LoanRequestNoCreditScoreDTO dto, SemaphoreSlim semaphore, IProgress<string> progress)
{
  await semaphore.WaitAsync();
  try
  {
    using (LoanBrokerWS.LoanBrokerWSClient client = new LoanBrokerWS.LoanBrokerWSClient())
    {
      var response = await RequestQuoteAsync(dto, client);
      progress.Report(response.SSN + "\n" + response.interestRate + "\n" + response.BankName + "\n------\n");
    }
  }
  catch (Exception ex)
  {
    progress.Report(ex.Message + "\n" + ex.InnerException.Message + "\n");
  }
  finally
  {
    semaphore.Release();
  }
}

If you call RequestQuote with await keyword then in every call it waits for the response and you can't make another. 如果您使用await关键字调用RequestQuote,则在每次调用中它都将等待响应,并且您无法进行其他响应。 so simply use your proxy's " completed event handler " for your async method and call RequestQuote method back to back and give your responses in the event handler. 因此,只需将代理的“ 完成的事件处理程序 ”用于异步方法,然后再调用RequestQuote方法并在事件处理程序中给出响应即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM