Hey I'm trying to access a method which is on another class rather than the one the thread was created on.. Now about the problem that I have to use delegates I fixed that infact the code works when i put the Print() message on the same class the thread is created on.
I tried a lot of possibilities including extending the MessagePrinter class as a subclass of the Form.. Please can any1 help how to solve this problem? cos I'm really gonna need it in the near future
In short all I want is to add text to a richtextbox via a thread which the method that does this is on another class.. The faulty code is shown below (with this i'm just getting the message "Starting Threads" in the rTextbox)
the code for the Form class:
Code:
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace CROSSTHREADING
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void SetText(string text)
{
if (this.richTextBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.richTextBox1.Text += text + '\n';
}
}
private void button1_Click(object sender, EventArgs e)
{
MessagePrinter printer1 = new MessagePrinter();
Thread thread1 = new Thread(new ThreadStart(printer1.Print));
Thread thread2 = new Thread(new ThreadStart(printer1.Print));
Thread thread3 = new Thread(new ThreadStart(printer1.Print));
thread1.Name = "thread1";
thread2.Name = "thread2";
thread3.Name = "thread3";
this.SetText("Starting Threads");
thread1.Start();
thread2.Start();
thread3.Start();
}
/*
//when i enable this method and call this method with the thread it works correctly
public void Print()
{
sleepTime = random.Next(5001);
Thread current = Thread.CurrentThread;
SetText(current.Name + " going to sleep for " + sleepTime.ToString());
//richTextBox1.Text = current.Name + " going to sleep for " + sleepTime.ToString();
Thread.Sleep(sleepTime);
SetText(current.Name + " done sleeping");
current.Abort();
//richTextBox1.Text = current.Name + " done sleeping";
}
* */
}
}
and the code for the MessagePrinter class is shown below:
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace CROSSTHREADING
{
class MessagePrinter : Form1
{
private int sleepTime;
private static Random random = new Random();
public MessagePrinter()
{
sleepTime = random.Next(5001);
}
public void Print()
{
sleepTime = random.Next(5001);
Thread current = Thread.CurrentThread;
SetText(current.Name + " going to sleep for " + sleepTime.ToString());
Thread.Sleep(sleepTime);
SetText(current.Name + " done sleeping");
current.Abort();
}
}
}