I'm using mysql .net connector
How to keep on checking if my application is connected to database, if it is connected run the select query and display some results. If it is not connected keep on checking until a connection is made and run the query.
I am having a hard time with this, I tired looking into while loops background workers but still can't wrap my head around this problem
CodePudding user response:
I am going to show you, how you can throttle your code. 2 ways. in Pseudo code:
1 - use a timer.
private timer;
void CallDB()
{
// connect and execute code gere
if (!success)
{
timer = new Timer(10000); // wait 10 sec
timer.MethodToExecute = TimerCall();
timer.Start();
}
}
void TimerCall()
{
timer.Stop();
timer.Dispose();
CallDB();
}
Above is the typical logic in pseudo code. If you fail the execution of connection-bound query, you start a timer and spin this thing until it completes, or you can add a variable which will reach certain count and exit.
2 - use Task scheduler
It will look something like this
private void Start()
{
var scheduler = CreateScheduler();
Task.Factory.StartNew(() => CallDb()}, scheduler )
.ContinueWith(() => { if (!success) Task.Run(() => Start()) });
}
Again, this is a pseudo code. It is not guarantee exact syntax but only a manner in which this can be done. Although it also can be done via queue.
CodePudding user response:
The idea of having the application checks the database connection every x time, is not a good idea. Instead, check the database connection before executing a query. Something like (pseudo code) :
if(IsConnected)
{
var queryResult = SqlQuery("SELECT * FROM table where Id between 1 AND 10");
if(queryResult != null)
{
// do your work
}
}
So, the question is how to check if the database connected or not ? simple, just use a simple query that should return a result (something like SELECT @@ROWCOUNT
) execute that query, and check the results, if the returned value matched the expected results then it's connected, otherwise it's not.
the idea can be constructed to something like this :
public bool IsConnected()
{
try
{
// should return 1
int result = (int) SqlScalar("SELECT @@ROWCOUNT");
return result == 1;
}
catch(Exception)
{
}
return false
}
Now, you can use IsConnected()
to check the connection status before each execution.