Привет всем
В этой теме я начинал обсуждение проблемы:
здесьАвтор: mra
Дата: 04.12.08
На данный момент выяснилось, что если на страничку моего приложения положить 2 прямых ссылки на файл, то они отлично скачиваются одновременно. То есть проблема на уровне кода.
Я попробовал запускать процесс скачивания в отдельном потоке, но это к сожалению работает не всегда. Подскажите пожалуйста если есть идеи, как лучше сделать?
Сейчас когд выглядит примерно так:
public void Download(string filePath, string fileName, string[] fileIds, long downloadLinkId, string downloadLinkName, string recipientName, string recipientEmail, FXDownloadLog.ViaTypes via, string notificationAdditionalInfo, HttpRequest Request, HttpResponse Response, System.Web.SessionState.HttpSessionState Session)
{
DownloadThread dt = new DownloadThread(filePath, fileName, fileIds, downloadLinkId, downloadLinkName, recipientName, recipientEmail, via, notificationAdditionalInfo, Request, Response, Session);
Thread dThread = new Thread(new ThreadStart(dt.DownloadThreadFunc));
dThread.SetApartmentState(ApartmentState.MTA);
dThread.Start();
// Без этой паузы диалог о сохранении файла не показывается, видимо какое-то время нужно на инициализацию нового потока
// или если показывается то файл не сохраняется, диалог сразу после начала скачивания говорит что скачивание закончено
Thread.Sleep(1000);
}
public class DownloadThread
{
private string filePath;
private string fileName;
private string[] fileIds;
private long downloadLinkId;
private string downloadLinkName;
private string recipientName;
private string recipientEmail;
private FXDownloadLog.ViaTypes via;
private string notificationAdditionalInfo;
private HttpRequest Request;
private HttpResponse Response;
private System.Web.SessionState.HttpSessionState Session;
public DownloadThread(string filePath, string fileName, string[] fileIds, long downloadLinkId, string downloadLinkName, string recipientName,
string recipientEmail, FXDownloadLog.ViaTypes via, string notificationAdditionalInfo, HttpRequest Request,
HttpResponse Response, System.Web.SessionState.HttpSessionState Session)
{
this.filePath = filePath;
this.fileName = fileName;
this.fileIds = fileIds;
this.downloadLinkId = downloadLinkId;
this.downloadLinkName = downloadLinkName;
this.recipientName = recipientName;
this.recipientEmail = recipientEmail;
this.via = via;
this.notificationAdditionalInfo = notificationAdditionalInfo;
this.Request = Request;
this.Response = Response;
this.Session = Session;
}
public void DownloadThreadFunc()
{
#region Local variables
int pos = 0;
long dataToRead = 0;
Stream stream = null;
string strRes = string.Empty;
#endregion
try
{
#region Download
GC.Collect();
fileName = HttpUtility.UrlPathEncode(fileName);
stream = new FileStream(filePath, FileMode.Open);
Response.Clear();
Response.AppendHeader("Content-Type", "application/OCTET-STREAM");
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
Response.AppendHeader("Content-Length", stream.Length.ToString());
Response.Buffer = true;
int length = 0;
dataToRead = stream.Length;
int size = FXTools.GetChunkSize(dataToRead);
byte[] buffer = new byte[size];
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = stream.Read(buffer, 0, size);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
dataToRead = dataToRead - length;
Thread.Sleep(100); // Замедление скачивания, чтобы было удобнее тестировать
if (dataToRead == 0)
{
try
{
(new FXDownloadLog(Session)).AddLogs(Session, fileIds, downloadLinkId, downloadLinkName, true, recipientName, recipientEmail, Request.UserHostAddress, via, notificationAdditionalInfo, true, ref strRes);
if (File.Exists(filePath)) File.Delete(filePath);
}
catch (Exception exp)
{
LogSys.LogError(string.Concat(LogPrefix, "Failed to send notification: ", exp.Message));
}
}
}
else
{
dataToRead = -1;
}
}
#endregion
}
catch (Exception exp)
{
#region
try
{
dataToRead = -1;
}
catch (Exception ex)
{
LogSys.LogError(string.Concat(LogPrefix, "Failed download: ", ex.Message));
}
#endregion
}
finally
{
#region
if (stream != null) stream.Close();
GC.Collect();
try
{
Response.End();
}
catch
{
}
#endregion
}
}
}