30
Jan
0
Silverlight – Thread And Timer (C#)
How to use thread and timer in C#/Silverlight.
Timer
System.Windows.Threading.DispatcherTimer timer;...timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 0, 0, duration); // duration in ms
timer.Tick+=new EventHandler(timer_Tick);timer.Start();
....
void timer_Tick(object sender, EventArgs e){
...
}
Tread
using System.Threading;
...
ThreadStart asyncMethod = new ThreadStart(Generate);
Thread thread = new Thread(asyncMethod);
thread.Start();
...
protected void Generate(){
...
}
Inter thread operation
When you use timer or thread, you may use cross thread functions. If you do that, you need to use the dispatcher as I do in the following example. In this example, I create an object Threaded. Threaded just request the mainpage to print a message on the screen.
//(Threaded.cs)
class Threaded{ // Basic class
MainPage page;
Threaded(MainPage parent){ // save main page
page = parent; // start thread
ThreadStart asyncMethod = new ThreadStart(PrintAMessage);
Thread thread = new Thread(asyncMethod);
thread.Start();
}
protected void PrintAMessage() { // ask to put a text to the screen
page.Print("Hey I am the thread!");
}
}
//(mainpage.xaml.cs)
public partial class MainPage : UserControl{
// code - constructor - etc...
.........
protected void StartThread(){ // create thread
Threaded th = new Threaded(this);
}
// called by thread
protected void Print(string mess){ // use dispatcher
Dispatcher.BeginInvoke(() =>
{
MyTextBox.Text = message;
});
}
}
Without dispatcher this example will fail, because we try to access data from a thread that is not allowed, only the proprietary thread can use it.
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
Subscribe to the RSS feed and have all new posts delivered straight to you.
