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 ?
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With