与TPL的两个不同呼叫的异步响应

与TPL的两个不同呼叫的异步响应

问题描述:

我有一个接受输入并向服务器发送异步请求的文本框。与TPL的两个不同呼叫的异步响应

首先我键入'a'并发送异步请求'a'。然后我立即键入'b'并发送'ab'请求。

'ab'的响应返回速度比'a'响应快。所以,我最终得到了响应“A”,即使文本框有值“AB”

我试图用,但它显示上次响应(这是“A”)

Task.Run(() => { 
     // send request 
}).ContinueWith((t) => { 
     // get response 
}); 

我有些newbiew 。任何人都可以帮助我如何处理这种情况?

您只需确保在发出新请求时可以可靠地取消先前的请求。这需要一些管道的,但一旦你让你的头周围的模式是不是很难:

CancellationTokenSource TextBoxCancellationTokenSource; 

async void TextBox_TextChanged() 
{ 
    // Harvest values needed to make the request *before* the first await. 
    string requestArg = TextBox.Text; 

    if (TextBoxCancellationTokenSource != null) 
    { 
     // Cancel previous request. 
     TextBoxCancellationTokenSource.Cancel(); 
    } 

    TextBoxCancellationTokenSource = new CancellationTokenSource(); 

    CancellationToken cancellationToken = TextBoxCancellationTokenSource.Token; 

    try 
    { 
     // Optional: a bit of throttling reducing the number 
     // of server requests if the user is typing quickly. 
     await Task.Delay(100, cancellationToken); 

     cancellationToken.ThrowIfCancellationRequested(); // Must be checked after every await. 

     var response = await Task.Run(() => GetResponse(requestArg), cancellationToken); 

     cancellationToken.ThrowIfCancellationRequested(); // Must be checked after every await. 

     ProcessResponse(response); 
    } 
    catch (OperationCanceledException) 
    { 
     // Expected. 
    } 
} 

免责声明:以上要求新的请求总是从一个单独的线程(UI线程最有可能的)排队。

+0

感谢您的回复。一个澄清,如果有三个请求'a','ab','abc',我最后的回应是'abc' - 使用取消将抛出异常两次(对于之前的'a'和'ab'),右? –

+2

@YeasinAbedinSiam,这取决于用户输入的速度。如果他们打字速度非常快,那么'a'和'ab'操作将被取消,是的。他们输入的越慢,越多的操作将实际运行到完成并最终进入“过程/显示响应”部分 - 没有例外。 –