I have a program that monitor a DB (or a number of DBs). for this, I built a class that holds all the information about how to monitor the DB. the class contains a delegate that points to a function that monitor the DB and changes the state field accordingly.
the main thread create a new instance of the class and calling the class.delegate.begininvoke(). the main thread checks the state of each created class in a loop and inform the user if any changes occur.
a simple example of the code:
Class Monitor
{
private Object lockObj;
private delegate void MonitorHandlerDelegate();
private MonitorHandlerDelegate mainHandler;
private int State;
private int DBid;
public Monitor(int DBid)
{
this.DBid = DBid;
mainHandler += MonitorHandler;
lockObj = new Object();
}
private void MonitorHandler()
{
do
{
state = CheckDB(DBid); // 0 is ok, 1 is fail, 2 is InWork, 3 is stop monitoring
} while (state != 3);
}
public int state
{
get { lock(lockObj) { return State;} }
set { lock(lockObj) {State = value;} }
}
public void Start()
{
this.state = 0;
this.mainHandler.BeginInvoke(null, null);
}
}
public Main()
{
Monitor firstMonitor = new Monitor(20);
firstMonitor.Start();
do
{
if(firstMonitor.state == 1) WriteLine("DB 20 stop working");
} while(true);
}
The problem I encountered is with exception handaling, if the MonitorHandler function throw an exception, i dont have a way to know it.
I dont call the EndInvoke so the exception is not re-throwing to the Main Thread.
My goal is to check the DB status by simply chack the state field of the monitor instance. If an exception in throwen i need to somehow "transfer" this exception to the Main Thread but i dont want to start checking the state and the Monitor delegate status as well.
I whold love to find a way to the Monitor Thread itself (the one that activated by the .BeginInvoke), to throw the exception in the Main Thread.
Thank you.