D
Dale Lundgren
I have a c# class library that launches a Win Form in a secondary thread.
From the Form (now running in the secondary thread) I need to be able to
start a method that is defined in the class and have it run in the main
thread.
I have read many examples and tried numerous approaches based on delegates
all of which will launch the method, but never in the main thread, always in
the secondary thread. Is what I'm trying to accomplish feasible?
Here's a quick example:
Class code:
namespace ThreadInvoke
{
public delegate void MyEventHandler(string txt);
public class Class1
{
Form2 myNewForm;
public Class1()
{
// Create instance of form to launch in new thread
myNewForm = new Form2(new MyEventHandler(LocalMethod));
}
public void LaunchThread()
{
// Create new thread, name it and start it
Thread myNewThread = new Thread(new ThreadStart(PopForm));
myNewThread.Name = "Secondary";
myNewThread.Start();
}
private void PopForm()
{
myNewForm.ShowDialog();
}
private void LocalMethod(string txt)
{
MessageBox.Show("Current Thread = " + Thread.CurrentThread.Name
+ "\nCalling Thread = " + txt);
}
}
}
Form Code (partial):
MyEventHandler localHandler;
public Form2(MyEventHandler EventRef)
{
InitializeComponent();
localHandler = EventRef;
}
private void button1_Click(object sender, System.EventArgs e)
{
localHandler(Thread.CurrentThread.Name);
}
Any help will be greatly appreciated!
Dale Lundgren
From the Form (now running in the secondary thread) I need to be able to
start a method that is defined in the class and have it run in the main
thread.
I have read many examples and tried numerous approaches based on delegates
all of which will launch the method, but never in the main thread, always in
the secondary thread. Is what I'm trying to accomplish feasible?
Here's a quick example:
Class code:
namespace ThreadInvoke
{
public delegate void MyEventHandler(string txt);
public class Class1
{
Form2 myNewForm;
public Class1()
{
// Create instance of form to launch in new thread
myNewForm = new Form2(new MyEventHandler(LocalMethod));
}
public void LaunchThread()
{
// Create new thread, name it and start it
Thread myNewThread = new Thread(new ThreadStart(PopForm));
myNewThread.Name = "Secondary";
myNewThread.Start();
}
private void PopForm()
{
myNewForm.ShowDialog();
}
private void LocalMethod(string txt)
{
MessageBox.Show("Current Thread = " + Thread.CurrentThread.Name
+ "\nCalling Thread = " + txt);
}
}
}
Form Code (partial):
MyEventHandler localHandler;
public Form2(MyEventHandler EventRef)
{
InitializeComponent();
localHandler = EventRef;
}
private void button1_Click(object sender, System.EventArgs e)
{
localHandler(Thread.CurrentThread.Name);
}
Any help will be greatly appreciated!
Dale Lundgren