1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class DataService { public async Task<string> FetchDataAsync(string id, CancellationToken token = default) { await Task.Delay(1000, token); return $"数据: {id}"; } public async Task<byte[]> DownloadWithProgressAsync( string url, IProgress<float> progress = null, CancellationToken token = default) { using var client = new HttpClient(); using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token); response.EnsureSuccessStatusCode(); var total = response.Content.Headers.ContentLength ?? -1; var buffer = new byte[8192]; var bytesRead = 0L; await using var stream = await response.Content.ReadAsStreamAsync(token); await using var memoryStream = new MemoryStream(); while (true) { int read = await stream.ReadAsync(buffer, token); if (read == 0) break; await memoryStream.WriteAsync(buffer.AsMemory(0, read), token); bytesRead += read; progress?.Report((float)bytesRead / total); } return memoryStream.ToArray(); } }
|