1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
        public void DownladAsync(string URL) {
            url = URL;

            try { File.Delete("test.flv"); } finally {}

            List<Thread> Threads = new List<Thread>();
            chunkOutput = new List<byte[]>();

            int totalChunks = 20;

            int start = 0;
            int end = 0;
            int fileSize = (int) ChunkDownloader.GetSize(URL);
            bool downloading = true;
            int i = 0;
            int lastpos = 0;
            bool endOfFile = false;

            while (!endOfFile) {
                Threads.Clear();
                chunkOutput.Clear();

                for (i = 0; i < totalChunks; i++) {
                    // run a thread and create empty slot for it
                    Thread chunkThread = new Thread(new ParameterizedThreadStart(DownloadSingleChunk));
                    Threads.Add(chunkThread);
                    chunkOutput.Add(new byte[0]);

                    // start and end position
                    start = lastpos + (i * chunkSize);
                    end = start + chunkSize;

                    // if does not have room for another chunk, stretch it until the end
                    if (start + (chunkSize * 2) > fileSize) {
                        //MessageBox.Show("THIS IS THE FINAL CHUNK");
                        chunkThread.Start(new object[] { i, start + 0, fileSize });
                        endOfFile = true;
                        break;
                    }

                    object[] parameters = null;
                    if (start == 0) 
                        parameters = new object[] { i, 0, chunkSize - 1};
                    else 
                        parameters = new object[] { i, start + 0, end - 1};

                    chunkThread.Start(parameters);
                }

                // wait for all chunks to finish
                foreach (Thread chunkThread in Threads) chunkThread.Join();

                lastpos += fromByteList(chunkOutput).Length; 
                ChunkDownloader.AppendData("test.flv", fromByteList(chunkOutput), fromByteList(chunkOutput).Length);
            }

            MessageBox.Show("Downloaded :)");

            foreach (Thread t in Threads) t.Interrupt();
        }