0

I have two datetimes. One is current and another is the datetime when race starts.Now I want check this Minutes difference continuously in background thread(I dont know about thread). And when it meets the if(remainingMinutes <=4) I want to update the UI. How to implement this with thread in background?

public RelayCommand OpenSetBets
    {
        get { return _setBets ?? (_setBets = new RelayCommand(ExecuteSetBets, CanExecuteSetBets)); }
    }

    private void ExecuteSetBets()
    {
        _navigation.NavigationToSetBetsDialogue();
    }

    private bool CanExecuteSetBets()
    {
        // Thread t = new Thread(newthread);
        double? remainingMinutes = null;

        if (UK_RaceDetail.Count() != 0)
        {
            //t.Start();                     
            DateTime CurrentUTCtime = DateTime.UtcNow;
            DateTime NextRaceTime = UK_RaceDetail[0].One.Time;
            remainingMinutes = NextRaceTime.Subtract(CurrentUTCtime).TotalMinutes;
        }

        if (remainingMinutes <= 4)
        {
            return true;
        }
        else
        {
            return false;
        }

    }

Updated Code. I want to enable button if race is going to start in next 4 minutes.

Dhruv Gohil
  • 842
  • 11
  • 34
  • From the code shown it's really unclear what you want, but either a WaitHandle or busy loop should do the trick. – CodeCaster Dec 21 '15 at 09:05
  • you can use timer for this , create a timer object with the difference of time you need to up date your UI some thing like this – kishore V M Dec 21 '15 at 09:05
  • timer = new Timer(1000); //here we set for 1 sec i.e 1000 milli seconds // here set time u need in ur case timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; static void timer_Elapsed(object sender, ElapsedEventArgs e) { // Here update ur ui } – kishore V M Dec 21 '15 at 09:05
  • let me know if that works for you i will add that as answer – kishore V M Dec 21 '15 at 09:06
  • @kishoreVM using timer can't really be an answer to question as it is asked now - "How to implement this with thread in background". (Indeed it is reasonable approach to problem that OP may be solving, but there is no comment in the question whether alternatives are acceptable or it is type of homework on background tasks) – Alexei Levenkov Dec 21 '15 at 09:10
  • Here in code,I have current time(CurrentUTCtime )and another time(NextRaceTime) when race will start.when 4 minutes to go to start race I want to push the if condition.I think for that I have to check this condition continuously because current time will be changed continuously. – Dhruv Gohil Dec 21 '15 at 09:10
  • This question is to broad. What do you mean by update UI, what data goes in the UI? You should take a look at Tasks if using .Net 4 (http://www.codeproject.com/Articles/691202/Using-the-Task-Parallel-Library-TPL-in-WPF), or even better C# async/await (http://www.codearsenal.net/2012/11/csharp-5-async-and-await-example.html?m=1) or use the WPF Dispatcher directly (https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher(v=vs.110).aspx) – Iñaki Elcoro Dec 21 '15 at 09:11
  • @kishoreVM Why not just supply your comment as an answer anyway? Comments aren't the best place to list source code. – Jason Evans Dec 21 '15 at 09:11
  • Yeah, you need to specify at the very least: .Net version and what technology your UI is. – zaitsman Dec 21 '15 at 09:14
  • 1
    You can use `ThreadPool` also. Here is a simple example:http://stackoverflow.com/questions/33316791/issue-with-updating-my-ui – Salah Akbari Dec 21 '15 at 09:23
  • How to use ThreadPool for my Code ?.@user2946329 – Dhruv Gohil Dec 21 '15 at 09:26
  • @DhruvGohil...Check that answer I mentioned. It contains a simple example and you can change it based on your needs. – Salah Akbari Dec 21 '15 at 09:28

2 Answers2

2

If you only want to use your background task to monitor the date/time, I recommend you not to create a new Thread.

For WPF, instead of thread, you can try to use DispatcherTimer object with its Tick event

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;

For WinForms, you can use Timer object with its Tick event

System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Tick += timer_Tick;

This way, you are rather saved from more complex solution using Thread or ThreadPool

Edit: to use Task.Delay, as some prefer this rather "cleaner" way, see the comment by Mr. Aron

Ian
  • 30,182
  • 19
  • 69
  • 107
  • Although this "technically works" I am at loathed to do upvote it. It would make much more sense to simply set a single Timer to run at the time you want. – Aron Dec 21 '15 at 09:15
  • You mean, you dislike the `Tick` event? – Ian Dec 21 '15 at 09:16
  • For example `await Task.Delay(raceStart - DateTimeNow)` – Aron Dec 21 '15 at 09:18
  • Ok, I believe it is also a good idea to use `Task.Delay`. It is "cleaner" some more. I refer my answer to your comment. – Ian Dec 21 '15 at 09:21
1

You can use Task.Run like,

System.Threading.Tasks.Task.Run(async () =>
{
    //starts running in threadpool parallelly
    while (!CanExecuteSetBets())
    {
        await Task.Delay(500); //wait 500 milliseconds after every check
    }

    DoYourWork(); //trigger your work here

}).ConfigureAwait(false);
mehmet mecek
  • 2,615
  • 2
  • 21
  • 25