BackgroundDownloader Max Parallelism

时间:2014-03-28 01:12:01

标签: c# windows-runtime winrt-async

有没有办法从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并设置最大金额,但我不知道这是否是一个很好的解决方案。

1 个答案:

答案 0 :(得分:0)

这就是我最终要做的事情。这还不完整,但它是它的要点。

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 );
    }
}