Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a method periodically from WPF client application using threading or timer [closed]

I am developing a WPF client application.This app sends data periodically to the webservice. When user logged into the app I want run particular method every 5 mts to send data to the .asmx service.

My question is whether I need to use threading or timer.This method execution should happen while user is interacting with the application. i.e without blocking the UI during this method execution

Any resources to look for ?

like image 977
umsateesh Avatar asked Jan 12 '13 18:01

umsateesh


People also ask

How to use thread in WPF?

This method is the starting point for the new thread. We create a new window under the control of this thread. WPF automatically creates a new Dispatcher to manage the new thread. All we have to do to make the window functional is to start the Dispatcher.

Is WPF single threaded?

The thread affinity is handled by the Dispatcher class, a prioritized message loop for WPF applications. Typically your WPF projects have a single Dispatcher object (and therefore a single UI thread) that all user interface work is channeled through.

Is WPF multi threaded?

WPF supports a single-threaded apartment model that has the following rules: One thread runs in the entire application and owns all the WPF objects. WPF elements have thread affinity, in other words other threads can't interact with each other.

What is thread affinity in WPF?

So thread affinity means that the thread, in this case the UI thread that instantiates an object is the only thread that can access its members. So for example, dependency object in WPF has thread affinity.


1 Answers

I would recommend the System.Threading.Tasks namespace using the new async/await keywords.

// The `onTick` method will be called periodically unless cancelled.
private static async Task RunPeriodicAsync(Action onTick,
                                           TimeSpan dueTime, 
                                           TimeSpan interval, 
                                           CancellationToken token)
{
  // Initial wait time before we begin the periodic loop.
  if(dueTime > TimeSpan.Zero)
    await Task.Delay(dueTime, token);

  // Repeat this loop until cancelled.
  while(!token.IsCancellationRequested)
  {
    // Call our onTick function.
    onTick?.Invoke();

    // Wait to repeat again.
    if(interval > TimeSpan.Zero)
      await Task.Delay(interval, token);       
  }
}

Then you would just call this method somewhere:

private void Initialize()
{
  var dueTime = TimeSpan.FromSeconds(5);
  var interval = TimeSpan.FromSeconds(5);

  // TODO: Add a CancellationTokenSource and supply the token here instead of None.
  RunPeriodicAsync(OnTick, dueTime, interval, CancellationToken.None);
}

private void OnTick()
{
  // TODO: Your code here
}
like image 151
Erik Avatar answered Sep 18 '22 07:09

Erik