|
|
|
C# WinApp WebClient.DownloadFileCompleted ไม่แน่ใจว่าโค้ดผิดตรงไหนครับ |
|
|
|
|
|
|
|
โค้ดเต็มๆ ครับ กำลังฝึก multi thread เพื่อทำงานพร้อมกันหลายๆ งานอยู่ครับ เผื่อใครอยากเอาไปใช้บ้าง
แต่ตอนนี้ยังไม่ เอา multi thread เข้ามาใช้นะครับ อยู่ในช่วงรันโค้ดดูว่าถ้า thread เดียวมันจะรันยังไง ครับ
Code (C#)
public class csharphelper_Loder:ProgressBar
{
public csharphelper_Loder():base()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
}
public event EventHandler DownloadDataCompleted;
protected virtual void OnDownloadDataCompleted(EventArgs e)
{
if (DownloadDataCompleted != null) DownloadDataCompleted(this, e);
}
public delegate void _DownloadDataCompletedEventHandler(object sender, EventArgs e);
public event EventHandler DownloadProgressChanged;
protected virtual void OnDownloadProgressChanged(EventArgs e)
{
if (DownloadProgressChanged != null) DownloadProgressChanged(this, e);
}
public delegate void _DownloadProgressChangedEventHandler(object sender, EventArgs e);
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Clear the background.
e.Graphics.Clear(this.BackColor);
// Draw the progress bar.
float fraction = (float)(this.Value - this.Minimum) / (this.Maximum - this.Minimum);
ProgressBarRenderer.DrawHorizontalBar(e.Graphics, new Rectangle(new Point(0, 0), this.Size));
ProgressBarRenderer.DrawHorizontalChunks(e.Graphics, new Rectangle(new Point(1, 1),
new Size((int)(((this.Size.Width - 2) / 100.0) * fraction), this.Size.Height - 2)));
int wid = (int)(fraction * this.ClientSize.Width);
e.Graphics.FillRectangle(
Brushes.LightGreen, 0, 0, wid,
this.ClientSize.Height);
// Draw the text.
e.Graphics.TextRenderingHint =
TextRenderingHint.AntiAliasGridFit;
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
if (Value == Maximum)
{
e.Graphics.DrawString("Complete...", this.Font, Brushes.Black, this.ClientRectangle, sf);
}
else
{
e.Graphics.DrawString((fraction).ToString("0.000 %") + " : " + Value + "/" + Maximum, this.Font, Brushes.Black, this.ClientRectangle, sf);
}
}
}
string getHTML(string url)
{
string html = "";
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url.Trim());
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
html = sr.ReadToEnd();
sr.Close();
response.Close();
}
catch { }
return html;
}
public async void Start()
{
int min = 1, max = 300;
Minimum = min;
Maximum = max;
await Task.Run(() =>
{
string fol = @"G:\csharphelper_Code";
System.IO.Directory.CreateDirectory(fol);
int i = 1;
do
{
int complete = 0;
string html = Program.getHTML("http://csharphelper.com/blog/page/" + i + "/");
MatchCollection _m = new Regex(@"a href=""(http://www.csharphelper.com/.*?\.zip)""><img border=", RegexOptions.None).Matches(html);
if (_m.Count <= 0)
{
i++;
try { this.Invoke(new Action(() => this.Value++)); } catch { }
}
else
{
foreach (Match myMatch in _m)
{
if (!System.IO.File.Exists(fol + System.IO.Path.GetFileName(myMatch.Groups[1].Value)))
{
using (WebClient wc = new WebClient())
{
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler((s, e) =>
{
complete++;
if (complete >= _m.Count)
{
System.Threading.Thread.Sleep(500);
i++;
try { this.Invoke(new Action(() => this.Value++)); } catch { }
}
});
wc.DownloadFileAsync(new Uri(myMatch.Groups[1].Value), fol + @"\" + System.IO.Path.GetFileName(myMatch.Groups[1].Value));
}
}
else
{
i++;
try { this.Invoke(new Action(() => this.Value++)); } catch { }
}
}
}
} while (i <= max);
});
}
}
ผมลองใช้
Code (C#)
wc.DownloadFile(new Uri(myMatch.Groups[1].Value), fol + @"\" + System.IO.Path.GetFileName(myMatch.Groups[1].Value));
มันรันทีละ 1 ก็จริงแต่ ค้างซะงั้น % มันไม่เพิ่มขึ้นเลยครับ
|
ประวัติการแก้ไข 2019-10-01 23:10:43 2019-10-01 23:50:25
|
|
|
|
Date :
2019-10-01 23:02:11 |
By :
lamaka.tor |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
complete ถูก reset เป็น 0 ที่ต้น Loop
โอกาสที่จะเกิด (complete >= _m.Count) มันอาจจะยาก
|
|
|
|
|
Date :
2019-10-02 10:20:41 |
By :
watcharop |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ถ้าต้องการโหลดทุกไฟล์พร้อมกัน ในแต่ละ Page
ใช้ DownloadFileTaskAsyncแทนก็น่าจะดี
Code (C#)
var dtasks = new List<Task>();
foreach (Match myMatch in _m)
{
if (!System.IO.File.Exists(fol + @"\" + System.IO.Path.GetFileName(myMatch.Groups[1].Value)))
{
sUrl = myMatch.Groups[1].Value;
sLog = string.Format("Downloading Page {0} / {1}\n", i, sUrl);
Debug.WriteLine(sLog);
try
{
var wc = new WebClient();
dtasks.Add(wc.DownloadFileTaskAsync(new Uri(myMatch.Groups[1].Value), fol + @"\" + System.IO.Path.GetFileName(myMatch.Groups[1].Value)));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
if (dtasks.Count > 0)
{
try
{
Task.WaitAll(dtasks.ToArray());
sLog = string.Format("Download completed Page {0}\n", i);
Debug.Print(sLog);
}
catch (Exception ex)
{
Debug.WriteLine("WaitAll Failed");
Debug.WriteLine(ex.Message);
for (int taskNo = 0; taskNo < dtasks.Count; taskNo++)
{
Debug.Print("{0}: Status: {1}, IsFaulted: {2}",
taskNo, dtasks[taskNo].Status, dtasks[taskNo].IsFaulted);
}
}
}
|
|
|
|
|
Date :
2019-10-02 10:56:38 |
By :
watcharop |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 04
|