Background Worker pada WP 7

Posted: March 1, 2013 by Sheilla Rizkia Ferianty in Windows Phone
Tags: ,

Capture

Background Worker memiliki fungsi yang hampir sama dengan Thread. Pada saat menjalankan aplikasi di Windows Phone, kita dapat menjalankan beberapa fungsi secara bersamaan. Misalnya fungsi timer dengan fungsi play sound berjalan secara beriringan dalam waktu yang sama.  Berikut kode lengkapnya:

namespace Publish
{
 public partial class Publish : PhoneApplicationPage
 {
 private BackgroundWorker bw1 = new BackgroundWorker(); //buat instansi dari kelas background worker
 private readonly Stopwatch My_stop_wtch = new Stopwatch(); //create stop watch
 private const string nolSound = "lagu1"; 
 private const string satuSound = "lagu2";
 private long last = 0;
 public Publish()
 {
 InitializeComponent();
 bw1.DoWork += new DoWorkEventHandler(bw1_DoWork); //event handler pada backround worker
 bw1.WorkerSupportsCancellation = true; //fungsi cancel background worker
 }
 private void bw1_DoWork(object sender, DoWorkEventArgs e)
 {
 My_stop_wtch.Start(); //stopwatch dimulai
 Song song = Song.FromUri(nolSound, new Uri("Resources/start.mp3", UriKind.Relative)); //memanggil lagu dari sumber file
 Song song1 = Song.FromUri(satuSound, new Uri("Resources/triidiot.mp3", UriKind.Relative));
 MediaPlayer.IsRepeating = false; //lagu tidak berulang
 MediaPlayer.Play(song); //play song
 System.Threading.Thread.Sleep(3000); //interval antar lagu
 MediaPlayer.Play(song1);
 }
 private void button1_Click(object sender, RoutedEventArgs e) //button untuk stop perhitungan waktu
 {
 if (My_stop_wtch.IsRunning) 
 {
 bw1.CancelAsync(); //fungsi cancel untuk background worker
 My_stop_wtch.Stop(); //fungsi stopwatch dimatikan
 long delta = Math.Abs(My_stop_wtch.ElapsedMilliseconds - last); //nilai absolut
 last = My_stop_wtch.ElapsedMilliseconds;
 t_waktu.Text = String.Format("{0} ms", delta); //cetak waktu henti pada textblock
 }
 else
 {
 t_waktu.Text = "Too fast!";
 }
 }
private void button2_Click(object sender, RoutedEventArgs e) //activate background worker
 {
 if (bw1.IsBusy != true)
 {
 bw1.RunWorkerAsync();
 }
 else
 {
 textBlock1.Text = "Gagal main";
 }
 }
 }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s