BackgoundWorker Use problem.

Jan 20 2010 8:43 PM
[C#]
I'm testing socket program(File download), I'm used 'BackgorundWorker' supplied by Net 4.0.

After I called 'RunWorkerAsync',  I have completed task (Do_Work of 'BackgroundWorker') and break loop.

Before loop break,  I printed MessageBox.Show("end").

However, MessageBox is showed two times.

I don't know the reason.

Please, Can anymore help me?

The source is following;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace WebClient
{

    public partial class Form1 : Form
    {
        FileStream fs;
        int totalsize;
        string download_filename;

        public Form1()
        {
            InitializeComponent();

            TreeNode mainNode = new TreeNode();
            mainNode.Name = "mainNode";
            mainNode.Text = "Download File List";
            this.treeView1.Nodes.Add(mainNode);

            TreeNode nextNode = new TreeNode();
            nextNode.Name = "nextNode";
            nextNode.Text = "Next";
            this.treeView1.Nodes.Add(nextNode);

            TreeNode subNode = new TreeNode();
            subNode.Name = "FILE01";
            subNode.Text = "TEST.csv";

            this.treeView1.Nodes[0].Nodes.Add(subNode);

            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            IPAddress serverIP = IPAddress.Parse(Program.IP);
            IPEndPoint serverEndPoint = new IPEndPoint(serverIP, Program.sPort);

            Program.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                ProtocolType.Tcp);
            Program.sock.Connect(serverEndPoint);

            if (Program.sock.Connected)
            {
                listBox1.Items.Add("normal connected.");
            }
            //while (true)
            //{
            byte[] setbyte = new byte[512];
            byte[] getbyte = new byte[512];
            setbyte = Encoding.UTF7.GetBytes("ID:minsoub");

            if (Program.sock.Send(setbyte, setbyte.Length, SocketFlags.None) < 0)
            {
                listBox1.Items.Add("Message send data error!!!");
            }
            // Ok msg get
            Program.sock.Receive(getbyte, 0, getbyte.Length, SocketFlags.None);
            listBox1.Items.Add(Encoding.UTF7.GetString(getbyte, 0, byteArrayDefrag(getbyte) + 1));
           
            // send want to FileName

            // get OK:FILE_SIZE
            //}
            Program.sock.Close();
        }

        public static int byteArrayDefrag(byte[] sData)
        {
            int endLength = 0;

            for (int i = 0; i < sData.Length; i++)
            {
                if ((byte)sData[i] != (byte)0)
                {
                    endLength = i;
                }
            }
            return endLength;
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode.Name.ToString().StartsWith("FILE"))
            {
                //listBox1.Items.Add(treeView1.SelectedNode.Name.ToString());
                //listBox1.Items.Add(treeView1.SelectedNode.Text.ToString());
            }
        }

        private void downLoadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("download starting............");

            IPAddress serverIP = IPAddress.Parse(Program.IP);
            IPEndPoint serverEndPoint = new IPEndPoint(serverIP, Program.sPort);

            Program.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                ProtocolType.Tcp);
            Program.sock.Connect(serverEndPoint);

            if (Program.sock.Connected)
            {
                listBox1.Items.Add("normal connected");
            }

            byte[] setbyte = new byte[512];
            byte[] getbyte = new byte[512];
            setbyte = Encoding.UTF7.GetBytes("ID:minsoub");

            if (Program.sock.Send(setbyte, setbyte.Length, SocketFlags.None) < 0)
            {
                listBox1.Items.Add("Message send data error!!!");
            }
            // Ok msg get
            Program.sock.Receive(getbyte, 0, getbyte.Length, SocketFlags.None);
            listBox1.Items.Add(Encoding.UTF7.GetString(getbyte, 0, byteArrayDefrag(getbyte) + 1));
            string ok = Encoding.UTF7.GetString(getbyte, 0, byteArrayDefrag(getbyte) + 1);
            if (ok == "OK")
            {
                // 2. send want to FileName
                setbyte = Encoding.UTF8.GetBytes("FILENAME:TB_CNTRYCD.csv");
                Program.sock.Send(setbyte, setbyte.Length, SocketFlags.None);
            }
                     
            // 3. get OK:FILE_SIZE
            Program.sock.Receive(getbyte, 0, getbyte.Length, SocketFlags.None);
            listBox1.Items.Add(Encoding.UTF7.GetString(getbyte, 0, byteArrayDefrag(getbyte) + 1));
            ok = Encoding.UTF7.GetString(getbyte, 0, byteArrayDefrag(getbyte) + 1);
            if (ok.StartsWith("OK"))
            {
                // File Size split
                string[] arr = ok.Split(':');
                listBox1.Items.Add("File size : " + arr[1]);

                progressBar1.Maximum = int.Parse(arr[1]);    // string ->int
                progressBar1.Value = 0;

                label3.Text = (int.Parse(arr[1]) / (1024 * 1024)).ToString();

                // 4. Download start message send
                setbyte = Encoding.UTF8.GetBytes("DOWNLOAD_START_FILE");
                Program.sock.Send(setbyte, setbyte.Length, SocketFlags.None);

                string fileName = "test.txt";

                if (System.IO.File.Exists(fileName))
                {
                    System.IO.File.Delete(fileName);
                }
                fs = File.Create(fileName);

                // 5. download start
                backgroundWorker1.RunWorkerAsync(int.Parse(arr[1]));
                // downloadFile(int.Parse(arr[1]));
            }
            else
            {
                listBox1.Items.Add("File size get error");
            }
           
        }
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Name.ToString().StartsWith("FILE"))
            {
                contextMenuStrip1.Enabled = true;
            }
            else
            {
                contextMenuStrip1.Enabled = false;
            }
        }

        private void downloadFile(int size)
        {
            int readByte = 0;
            byte[] getbyte = new byte[512];

            while (true)
            {
                Program.sock.Receive(getbyte, 0, getbyte.Length, SocketFlags.None);
                readByte = byteArrayDefrag(getbyte);
                totalsize += readByte;

                if (readByte <= 0) break;

                // write file
                fs.Write(getbyte, 0, readByte);

                if (totalsize >= size) // progressBar1.Maximum)
                {
                    MessageBox.Show("End...");
                    backgroundWorker1.ReportProgress(size);
                    break;
                }
                backgroundWorker1.ReportProgress(totalsize);
                // Thread.Sleep(-1);

                // progressBar1.Value = totalsize;
            }
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Object argument = e.Argument;
            int size = (int)argument;

            downloadFile(size);
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label5.Text = (totalsize / (1024 * 1024)).ToString();
            if (e.ProgressPercentage >= progressBar1.Maximum)
            {
                progressBar1.Value = progressBar1.Maximum;
            }
            else
            {
                progressBar1.Value = e.ProgressPercentage;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            byte[] setbyte = new byte[512];

            if (e.Cancelled == true)
            {
                fs.Close();
                listBox1.Items.Add("User Canceled....");
                Program.sock.Close();
            }
            else
            {

                fs.Close();
                listBox1.Items.Add("Total Byte : " + totalsize);

                // 6. completed message send
                setbyte = Encoding.UTF8.GetBytes("DW_COMPLATED");
                Program.sock.Send(setbyte, setbyte.Length, SocketFlags.None);

                Program.sock.Close();
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            downLoadToolStripMenuItem_Click(sender, e);
        }

 
    }
}

Answers (1)