Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I run a stored procedure that takes 5 minutes to complete, will my code sequence continue before the stored procedure is complete?

Tags:

c#

If I have a program that runs a stored procedure that takes about 5 minutes to run, for example:

Database.RunJob(); -- takes 5 mins to complete
MessageBox.Show("Hi");

Question - is the message box going to show "Hi" BEFORE Database.RunJob() is complete?

If it does, how do I make sure a query is complete before proceeding to the next line of code?

like image 926
JJ. Avatar asked Dec 20 '22 18:12

JJ.


1 Answers

Insufficient information to give meaningful answer.

The best answer we can give is: it depends on whether Database.RunJob() is synchronous or asynchronous.

  • If .RunJob is synchronous (that is, run on the current thread), then MessageBox.Show will not run until the .RunJob finishes.

  • If it's asynchronous, spawning other thread(s) to do the work, then MessageBosh will execute immediately, before the job is finished.

Since you didn't show what RunJob actually does, we can't answer any more precisely.


Let's suppose .RunJob is asynchronous. If the designer of that method was worth his salt, he would return something from that method; ideally a Task<T>.

If he returns a Task, you could do write your C# 5 code like this:

async void RunJobAndShowSuccessMessage()
{
     await Database.RunJob();
     MessageBox.Show("Hi, the job is done!");
}

Let's suppose .RunJob is synchronous, running only on the current thread. This means you probably don't want to run it on the UI thread; doing so will cause your application UI to freeze for 5 minutes.

To avoid that scenario, let's run the database job on a different thread ourselves, so that the application UI remains responsive:

async void RunJobAndShowSuccessMessage()
{
    // Spawn a task to run in the background.
    await Task.Factory.Start(() => Database.RunJob());
    MessageBox.Show("Hi, the job is done!");
}
like image 198
Judah Gabriel Himango Avatar answered Dec 30 '22 11:12

Judah Gabriel Himango