0
我對於異步任務有點陌生。C#同時運行許多異步任務
我有一個功能,可以從特定的大學網站上獲取學生證和數據,並提供所需的ID。
private static HttpClient client = new HttpClient();
public static async Task<Student> ParseAsync(string departmentLink, int id, CancellationToken ct)
{
string website = string.Format(departmentLink, id);
try
{
string data;
var stream = await client.GetAsync(website, ct);
using (var reader = new StreamReader(await stream.Content.ReadAsStreamAsync(), Encoding.GetEncoding("windows-1256")))
data = reader.ReadToEnd();
//Parse data here and return Student.
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
它正常工作。雖然有時我需要爲很多學生運行這個功能,所以我用下面的
for(int i = ids.first; i <= ids.last; i++)
{
tasks[i - ids.first] = ParseStudentData.ParseAsync(entity.Link, i, cts.Token).ContinueWith(t =>
{
Dispatcher.Invoke(() =>
{
listview_students.Items.Add(t.Result);
//Students.Add(t.Result);
//lbl_count.Content = $"{listview_students.Items.Count}/{testerino.Length}";
});
});
}
我存儲在數組任務後等待他們。
只要學生人數介於(0,〜600?)之間,這也可以很好地工作,這是隨機的。 然後對於仍然沒有被解析過的所有其他學生拋出任務被取消。
請記住,我從不使用取消標記。
我需要在如此多的學生上運行這個函數,它可以完全達到〜9000個異步任務。那麼發生了什麼?