Question

I am making a turn based silverlight game(Cards game). and I want to delay between turns.

I've tried the Thread.Sleep, but it halts my UI. I've tried to use DispatcherTimer, but it acts funny. sometimes it works, sometimes it skips.

My code works perfectly with DipatcherTimer when i set the Interval to 3 seconds, but when i set the interval to 1 second, it starts to skip some rounds.

Is there another way to create this delay?

Update: I just restarted my windows, and it worked perfectly for a while. One hour later, I tried again, without changing the code, it started skipping! i dont get it.

Was it helpful?

Solution

You can use the System.Threading.Timer class with the understanding that it uses threads (as seen below). The timer is setup in the constructor. It starts immediately (the third parameter set to 0), and then executes every 1000ms (4th param). Inside, the code immediately calls the Dispatcher to update the UI. The potential benefit of this is that you're not tying up the UI thread for busy work that could be done in another thread (without using a BackgroundWorker for example).

using System.Windows.Controls;
using System.Threading;

namespace SLTimers
{
    public partial class MainPage : UserControl
    {
        private Timer _tmr;
        private int _counter;
        public MainPage()
        {
            InitializeComponent();
            _tmr = new Timer((state) =>
            {
                ++_counter;
                this.Dispatcher.BeginInvoke(() =>
                {
                    txtCounter.Text = _counter.ToString();
                });
            }, null, 0, 1000);            
        }
    }
}

<UserControl x:Class="SLTimers.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="txtCounter"  Margin="12" FontSize="80" Text="0"/>
    </Grid>
</UserControl>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top