Hi Guys,
On the subject of threading, I am trying to create a code driven animation using the System.Threading.Timer class. The problem is Timer callbacks run from another thread, so when I try to move and element I am getting "Invalid Cross-Thread access".
Is there a way to create a thread safe heartbeat?
Here is some sample code to replicate the issue
------- XAML-----------
<Canvas x:Name="parentCanvas"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="Page_Loaded"
x:Class="SilverlightProject1.Page;assembly=ClientBin/SilverlightProject1.dll"
Width="640"
Height="480"
Background="White"
>
<Ellipse Canvas.Top="100" Canvas.Left="100" Fill="Black" Width="10" Height="10" x:Name="elpBall"></Ellipse>
</Canvas>
-----------------------------
------------------- Code------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
namespace SilverlightProject1
{
public class Page : Canvas
{
Ellipse elpBall;
private Timer timer;
public void Page_Loaded(object o, EventArgs e)
{
elpBall = this.FindName("elpBall") as Ellipse;
timer = new Timer(Move, null, 1, -1);
}
private void Move(Object state)
{
this.elpBall.SetValue(Canvas.LeftProperty, 5);
}
}
}
-------------------------------------
Cheers,
Javier