gpt4 book ai didi

c# - 异步任务暂停循环恢复

转载 作者:行者123 更新时间:2023-12-02 17:41:27 25 4
gpt4 key购买 nike

<分区>

我有一个示例代码,取自 MSDN,我想在其中实现 while 循环中的暂停/恢复功能。任何人都可以提出一个解决方案/parern 来解决这个问题吗?

 private async void startButton_Click(object sender, RoutedEventArgs e)
{
resultsTextBox.Clear();

// Instantiate the CancellationTokenSource.
cts = new CancellationTokenSource();

try
{
await AccessTheWebAsync(cts.Token);
resultsTextBox.Text += "\r\nDownloads complete.";
}
catch (OperationCanceledException)
{
resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
}
catch (Exception)
{
resultsTextBox.Text += "\r\nDownloads failed.\r\n";
}

cts = null;
}


private void cancelButton_Click(object sender, RoutedEventArgs e)
{
if (cts != null)
{
cts.Cancel();
}
}


async Task AccessTheWebAsync(CancellationToken ct)
{
HttpClient client = new HttpClient();

// Make a list of web addresses.
List<string> urlList = SetUpURLList();

// ***Create a query that, when executed, returns a collection of tasks.
IEnumerable<Task<int>> downloadTasksQuery =
from url in urlList select ProcessURL(url, client, ct);

// ***Use ToList to execute the query and start the tasks.
List<Task<int>> downloadTasks = downloadTasksQuery.ToList();

// ***Add a loop to process the tasks one at a time until none remain.
while (downloadTasks.Count > 0)
{
// Identify the first task that completes.
Task<int> firstFinishedTask = await Task.WhenAny(downloadTasks);

// ***Remove the selected task from the list so that you don't
// process it more than once.
downloadTasks.Remove(firstFinishedTask);

// Await the completed task.
int length = await firstFinishedTask;
resultsTextBox.Text += String.Format("\r\nLength of the download: {0}", length);
}
}

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