I am looking for a solution for Interthread communication. We got a Three Tier Architecture,
Gui, references Logic references Devicecontroller
Thread A is the main thread of a windows app. I starts a Thread B that is working independant of thread a, they do not share code. But thread A has to get some feedback about status of thread b. I try to solve this with a delegate. I have to work on .net 3.5, c#, WEC7
Gui and Logic run in context of Thread A DeviceController runs in Context of Thread B. Both Threads are long running Thread A starts and controls Thread B. Thread A (Logic) gets information back from B (DeviceController) and updates the Gui or the database
It is important that the code is executed in Thread A
public void OnMyEvent(string foo)
{
//there may be access to Gui here, there may be other actions, like accessing database
// All this should be in context of thread A
MessageBox.Show(foo);
}
// The Gui
namespace WindowsFormsApplication1
{
//This code is executed in Thread A, UIThread
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadController threadController = new ThreadController();
threadController.StartThread(this, e);
}
}
}
//Tier Logic, runs in Context of Thread A
namespace Logic
{
//this class runs in the context of Thread A
public class ThreadController
{
public void StartThread(Object obj)
{
new ClassForSecondThread(obj as Parameters);
}
public void StartThread(object sender, EventArgs e)
{
//ParameterizedThreadStart threadstart = new ParameterizedThreadStart(startThread);
ParameterizedThreadStart threadstart = new ParameterizedThreadStart(StartThread);
Thread thread = new Thread(threadstart);
Parameters parameters = new Parameters() {MyEventHandler = OnMyEvent};
thread.Start(parameters);
}
public void OnMyEvent(string foo)
{
//there may be access to Gui here, there may be other actions, like accessing database
// All this should be in context of thread A. Here it is unfortunately in Context Thread B
MessageBox.Show(foo);
}
}
}
//runs in context of Thread B namespace DeviceController {
//This class runs in the context of Thread B
public class ClassForSecondThread
{
public ClassForSecondThread(Parameters parameters)
{
if (parameters == null)
return;
MyEventhandler += parameters.MyEventHandler;
DoWork();
}
private void DoWork()
{
//DoSomething
if (MyEventhandler != null)
MyEventhandler.DynamicInvoke("Hello World");
Thread.Sleep(10000);
if (MyEventhandler != null)
MyEventhandler.DynamicInvoke("Hello World again");
}
private event MyEventHandler MyEventhandler;
}
public class Parameters
{
public MyEventHandler MyEventHandler;
}
public delegate void MyEventHandler(string foo);
}
There are two issues, I cannot yet handle:
No 1: OnMyEvent still runs in context of thread b No 2: I need the same communication the other way, if there is some event in the gui, the devicecontroller has to be informed about e.g. shutdown etc.