ダウンロードファイルにthiseコードを使用します:
public delegate void ReportProgerssDelegate(int progerss);
public class TestFileDownloader
{
public ReportProgerssDelegate ReportProgerss;
public void startHTTPDownload(string urlToReadFileFrom, string filePathToWriteFileTo)
{
Uri _url = new Uri(urlToReadFileFrom);
System.Net.HttpWebRequest _request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(_url);
System.Net.HttpWebResponse _response = (System.Net.HttpWebResponse)_request.GetResponse();
Int64 _downloadedFileSize = _response.ContentLength;
Int64 _totalNumberOfReadedBytes = 0;
using (System.Net.WebClient _webClient = new System.Net.WebClient())
{
using (System.IO.Stream _streamRemote = _webClient.OpenRead(new Uri(urlToReadFileFrom)))
{
using (Stream _streamLocal = new FileStream(filePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
{
int _numberOfReadedBytes = 0;
byte[] _byteBuffer = new byte[1024];
while ((_numberOfReadedBytes = _streamRemote.Read(_byteBuffer, 0, _byteBuffer.Length)) > 0)
{
_streamLocal.Write(_byteBuffer, 0, _numberOfReadedBytes);
_totalNumberOfReadedBytes += _numberOfReadedBytes;
reportProgress(_totalNumberOfReadedBytes, _downloadedFileSize);
}
_streamLocal.Close();
}
_streamRemote.Close();
}
}
reportProgress(100, 100);
}
private void reportProgress(long totalNumberOfReadedBytes, long downloadedFileSize)
{
double _index = (double)(totalNumberOfReadedBytes);
double _total = (double)downloadedFileSize;
double _progress = (_index / _total);
int _progressPercentage = (int)(_progress * 100);
if (ReportProgerss != null)
ReportProgerss(_progressPercentage);
}
}
単一のタスクとして開始すると、完璧に機能します。
TestFileDownloader _fd1 = new TestFileDownloader();
_fd1.ReportProgerss = reportProgress;
Task _task = new Task(
() => _fd1.startHTTPDownload("http://",
@"d:\..."));
_task.Start();
このように使用しようとすると:
TestFileDownloader _fd1 = new TestFileDownloader();
_fd1.ReportProgerss = reportProgress;
TestFileDownloader _fd2 = new TestFileDownloader();
_fd2.ReportProgerss = reportProgress;
TestFileDownloader _fd3 = new TestFileDownloader();
_fd3.ReportProgerss = reportProgress;
Task _task = new Task(
() => _fd1.startHTTPDownload("http://",
@"d:\..."));
_task.Start();
Task _task2 = new Task(
() => _fd2.startHTTPDownload("http://",
@"d:\..."));
_task2.Start();
Task _task3 = new Task(
() => _fd3.startHTTPDownload("http://",
@"d:\..."));
_task3.Start();
タイムアウトになりました。
なにが問題ですか?