Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > .NET Framework > Forum > C# WinApp WebClient.DownloadFileCompleted ไม่แน่ใจว่าโค้ดผิดตรงไหนครับ



 

C# WinApp WebClient.DownloadFileCompleted ไม่แน่ใจว่าโค้ดผิดตรงไหนครับ

 



Topic : 134283



โพสกระทู้ ( 4,436 )
บทความ ( 23 )



สถานะออฟไลน์
Facebook



แห3

Code (C#)
 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);

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


            });

        }


ทั้งๆที่ในโค้ด ก็ ระบุไว้แล้ว ถ้า DownloadFileCompleted ค่อยให้ i++
เลยไม่รู้ผิดตรงไหนทำไมถึงโหลดต่อเนื่องกันเลย ครับ โดยไม่รอให้โหลดเสร็จก่อน ครับ



Tag : .NET, C#, VS 2015 (.NET 4.x)







Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2019-10-01 22:15:22 By : lamaka.tor View : 816 Reply : 5
 

 

No. 1



โพสกระทู้ ( 4,436 )
บทความ ( 23 )



สถานะออฟไลน์
Facebook

โค้ดเต็มๆ ครับ กำลังฝึก 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 ก็จริงแต่ ค้างซะงั้น % มันไม่เพิ่มขึ้นเลยครับ

323








ประวัติการแก้ไข
2019-10-01 23:10:43
2019-10-01 23:50:25
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2019-10-01 23:02:11 By : lamaka.tor
 


 

No. 2



โพสกระทู้ ( 1,348 )
บทความ ( 1 )



สถานะออฟไลน์


complete ถูก reset เป็น 0 ที่ต้น Loop
โอกาสที่จะเกิด (complete >= _m.Count) มันอาจจะยาก
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2019-10-02 10:20:41 By : watcharop
 

 

No. 3



โพสกระทู้ ( 4,436 )
บทความ ( 23 )



สถานะออฟไลน์
Facebook

ตอบความคิดเห็นที่ : 2 เขียนโดย : watcharop เมื่อวันที่ 2019-10-02 10:20:41
รายละเอียดของการตอบ ::
เอ๋.......
แต่ว่า แต่ละ loop ผมก็แยกกันนะครับ(ไม่ได้ใช่ไม๊ครับ)

เราควรแก้เป็นยังไงดีครับ

แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2019-10-02 10:27:46 By : lamaka.tor
 


 

No. 4



โพสกระทู้ ( 1,348 )
บทความ ( 1 )



สถานะออฟไลน์


ถ้าต้องการโหลดทุกไฟล์พร้อมกัน ในแต่ละ 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
 


 

No. 5



โพสกระทู้ ( 4,436 )
บทความ ( 23 )



สถานะออฟไลน์
Facebook

ตอบความคิดเห็นที่ : 4 เขียนโดย : watcharop เมื่อวันที่ 2019-10-02 10:56:38
รายละเอียดของการตอบ ::
ผมไม่อยากให้มันโหลดพร้อมกัน หรือไม่ก็โหลดทีละ 5 หรือ 10 ประมาณนี้ครับ


แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2019-10-02 11:55:57 By : lamaka.tor
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : C# WinApp WebClient.DownloadFileCompleted ไม่แน่ใจว่าโค้ดผิดตรงไหนครับ
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: นำเข้าสินค้าจากจีน, Taobao, เฟอร์นิเจอร์, ของพรีเมี่ยม, ร่ม, ปากกา, power bank, แฟลชไดร์ฟ, กระบอกน้ำ

Load balance : Server 05
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่