BackgroundDownloader最大并行度

本文关键字:并行度 BackgroundDownloader | 更新日期: 2023-09-27 17:54:46

是否有办法设置BackgroundDownloader的最大并发下载数?

这就是我正在做的。

var downloader = new BackgroundDownloader();
foreach( var uri in uriList )
{
    var download = downloader.CreateDownload( uri, storageFile );
    download.StartAsync().AsTask( cancellationTokenSource.Token, progress );
}

我希望能够设置最大下载并行度为4。这是内置的,还是我需要自己管理?

如果我需要自己管理,推荐的方法是什么?我想过只是做一个Parallel.ForEach并设置最大金额,但我不知道这是不是一个好的解决方案。

BackgroundDownloader最大并行度

这就是我最后所做的。这不是完整的,但它是它的要点。

private void StartDownloadsAsync()
{
    var downloadQueue = new Queue<DownloadOperation>();
    // Create all the download operations and add them to the queue.
    await CreateDownloadsAsync();
    var maxConcurrentDownloads = 4;
    var loopAmount = Math.Min( maxConcurrentDownloads, downloadQueue.Count );
    for( var i = 0; i < loopAmount; i++ )
    {
        DownloadAsync();
    }
}
private void DownloadAsync()
{
    var download = downloadQueue.Dequeue();
    HandleDownloadAsync( download ).ContinueWith( task => DownloadComplete( download ) );
}
private void DownloadComplete( DownloadOperation download )
{
    // Update progress counter here.
    if( downloadQueue.Count > 0 )
    {
        DownloadAsync();
    }
    else
    {
        // Downloads are done. Do something.
    }
}
private async Task HandleDownloadAsync( DownloadOperation download, bool isActive = false )
{
    if( !isActive )
    {
        await download.StartAsync().AsTask( cancellationTokenSource.Token );
    }
    {
        await download.AttachAsync().AsTask( cancellationTokenSource.Token );
    }
}