我有azure A4基本机器(8芯)来测试我的应用程序:
namespace DownloadSomeData
{
internal class FileDownloader
{
int nextIndex = 0;
int _ListSize;
readonly uint MaxConcurrentDownloads = 0;
private IList<MyModel> _ValidList;
public FileDownloader(uint maxConcurrentThread, IList<MyModel> list)
{
_ValidList = list;
MaxConcurrentDownloads = maxConcurrentThread;
//Get the items count
_ListSize = _ValidList.Count();
}
/// <summary>
///
/// </summary>
public async Task Start()
{
uint parallelThreads = MaxConcurrentDownloads;
if (_ListSize < MaxConcurrentDownloads)
{
parallelThreads = (uint)_ListSize;
}
// Now, start the downloads.
for (int i = 0; i < parallelThreads; ++i)
{
var client = GetNextWebClient();
MyModel nextObject = _ValidList.ElementAt(i);
StartDownload(client, nextObject);
nextIndex++;
}
}
private WebClient GetNextWebClient()
{
var client = new WebClient();
client.DownloadProgressChanged += DownloadProgressChanged;
client.DownloadFileCompleted += DownloadFileCompleted;
return client;
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
private void StartDownload(WebClient client, MyModel state)
{
try
{
string fname = state.ImageFilename;
state.DownloadStatus = EnumDownloadStatus.Started;
client.DownloadFileAsync(new Uri(state.ImageUri), fname, state); // start the asynchronous download.
}
finally
{
if (client != null)
{
client.Dispose();
}
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// Progress tracking here
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
var model = (MyModel)e.UserState;
if (e.Error != null)
{
}
else if (e.Cancelled == true)
{
}
else
{
}
var index = nextIndex;
if (index < _ListSize)
{
MyModel nextObject = _ValidList.ElementAt(index);
nextIndex = nextIndex + 1;
StartDownload(GetNextWebClient(), nextObject);
}
}
}}
此代码始终执行2或最多3个并行文件下载。即使在i5(4核)机器上我也有同样的行为。 实际上我在i5机器上运行了一些其他应用程序。但除此之外,azure机器没有其他程序在运行。
我使用以下方法调用此代码:
private async Task StartDownload
{
FileDownloader download = new FileDownloader(_ConcurrentThread, _List);
await download.Start();
}
我是否编写了写入逻辑以将最大内核用于应用程序?