Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public delegate void TestDeleg(string message);
- public class Data
- {
- public TestDeleg deleg;
- public string mess;
- }
- class test
- {
- public List<Thread> threads = new List<Thread>();
- public int nThreads = 0;
- public int maxThreads = 5;
- public void DoWork(object data)
- {
- Data d = (Data)data;
- d.deleg(d.mess);
- //string message = (string)data;
- //MessageBox.Show(d.mess);
- return;
- }
- public void CreateThread(object data)
- {
- if (nThreads >= maxThreads)
- return;
- Thread newThread = new Thread(DoWork);
- threads.Add(newThread);
- newThread.IsBackground = true;
- newThread.Start(data);
- nThreads++;
- }
- public void WindUpThreads()
- {
- //MessageBox.Show("count: " + nThreads.ToString());
- for(int i = 0; i < threads.Count; i++)
- {
- if (threads[i].IsAlive == false)
- {
- threads[i].Abort();
- threads.RemoveAt(i);
- //MessageBox.Show("removing at " + i.ToString());
- }
- }
- nThreads = threads.Count;
- }
- }
- private void button1_Click(object sender, EventArgs e)
- {
- button1.Enabled = false;
- test thTest = new test();
- string[] strings;
- try
- {
- strings = File.ReadAllLines("C:\\users\\alex\\desktop\\test.txt");
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- return;
- }
- bool flag = true;
- int counter = 0;
- int dataCount = strings.Length;
- while (flag == true)
- {
- if (counter >= dataCount)
- {
- flag = false;
- }
- while (thTest.nThreads < thTest.maxThreads)
- {
- if (flag == false)
- break;
- //thTest.CreateThread(strings[counter]);
- Data d = new Data();
- d.deleg = AddItem;
- d.mess = strings[counter];
- thTest.CreateThread((object)d);
- //MessageBox.Show(counter.ToString());
- counter++;
- }
- thTest.WindUpThreads();
- if (flag == false)
- {
- do
- {
- thTest.WindUpThreads();
- } while (thTest.nThreads != 0);
- }
- }
- listBox1.Items.Add("Done");
- }
- public void AddItem(string message)
- {
- lock(obj)
- {
- if(listBox1.InvokeRequired)
- Invoke( (Action)( () => { listBox1.Items.Add(message); } ) );
- //listBox1.BeginInvoke(new Action <string>(AddItem), message);
- else
- listBox1.Items.Add(message);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement