Search code examples
c#background-processwindows-8.1

Scheduling a timed background task in windows 8.1 store app


I have a list of of StringsDouble called Messages.

The code for the class is below:

public class StringsDouble
{
    public string Sender {get; set;}

    public string Message {get; set;}

    public DateTime Time {get; set;}  
}

every time my app receives a new message. I update the List and i store the time of the latest message sent for the user sending that message.

what i want to do is, every 5 minutes the app should go through the list.

and for every item in the list it should get the time property and get the current system time , and check to see if the difference is more than 30 minutes. If it is, it should delete that item from the list.

How can i accomplish this?

I believe i need to use a background task, but how can i schedule it to run every 5 minutes?


Solution

  • You can use DispatcherTimer on UI thread:

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromMinutes(5);
    timer.Tick += (sender, e) =>
    {
        //...
    };
    timer.Start();
    

    or ThreadPoolTimer on a background thread:

    ThreadPoolTimer threadPoolTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
    {
        //...            
    }, TimeSpan.FromMinutes(5));