gpt4 book ai didi

c# - 从方法外部取消 GetAsync 请求

转载 作者:行者123 更新时间:2023-11-30 19:16:44 30 4
gpt4 key购买 nike

我有大量的异步请求。在某些时候,当应用程序被停用(暂停)时,我需要取消所有请求。我正在寻找一种解决方案来取消异步方法之外的请求。有人可以指出我正确的方向吗?

这是代码块。

异步方法:

public async void GetDetailsAsync(string url)
{
if (this.LastDate == null)
{
this.IsDetailsLoaded = "visible";
NotifyPropertyChanged("IsDetailsLoaded");
Uri uri = new Uri(url);
HttpClient client = new HttpClient();
HtmlDocument htmlDocument = new HtmlDocument();
HtmlNode htmlNode = new HtmlNode(0, htmlDocument, 1);
MovieData Item = new MovieData();
string HtmlResult;

try
{
HtmlRequest = await client.GetAsync(uri);
HtmlResult = await HtmlRequest.Content.ReadAsStringAsync();
}
...

调用方法:

for (int i = 0; i < App.ViewModel.Today.Items.Count; i++)
{
App.ViewModel.Today.Items[i].GetDetailsAsync(App.ViewModel.Today.Items[i].DetailsUrl);
}

停用事件:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
//Here i need to stop all requests.
}

最佳答案

你只是create a single (shared) instance of CancellationTokenSource :

private CancellationTokenSource _cts = new CancellationTokenSource();

然后,tie all asynchronous operations into that token :

public async void GetDetailsAsync(string url)
{
...
HtmlRequest = await client.GetAsync(uri, _cts.Token);
...
}

最后,在适当的时候取消CTS:

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
_cts.Cancel();
_cts = new CancellationTokenSource();
}

关于c# - 从方法外部取消 GetAsync 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21786465/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com