Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So you start out by saying that you want to perform a task every X seconds. That tells us that we need a timer. There are a lot to choose from though. <code>System.Timer</code> should work fine for our purposes, but if you want to use the <code>System.Windows.Forms.Timer</code> you can. You'll want to start the timer when you open the form, configure the interval to what you want, and assign a handler to run when the timer fires.</p> <p>Next, when the timer fires you need to perform a database call and update the UI. Performing a long running operation and then updating the UI with the results is what the <code>BackgroundWorker</code> class was tailor made for. Set the <code>DoWork</code> method to do your database call, and have the <code>WorkerCompleted</code> event update the UI based on the results. (The completed event will automatically be run in the UI thread; you don't need to manually marshal to that thread.)</p> <p>You could also use Tasks to do these same things, if you have a new enough version of C#. You could use <code>Task.Factory.StartNew</code> for the database call to have it run in a background thread, and then you can call <code>ContinueWith</code> on the <code>Task</code> it returns and use the overload that allows you to specify a synchronization context. Here's a simple example:</p> <pre><code>private void handler(object sender, EventArgs e) { Task.Factory.StartNew(() =&gt; getInfoFromDB()) .ContinueWith(task =&gt; label1.Text = task.Result, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); } private string getInfoFromDB() { Thread.Sleep(2000);//simulate long IO operation return "Hello world!"; } </code></pre> <p>Note that for this <code>Task</code> based example to work you would need to use the <code>System.Windows.Forms.Timer</code> timer, so that the tick event runs in the UI thread.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload