Reputation: 125
I am hitting a wall and have come here hoping you guys can help me out with the following:
I am designing a wp7 app where I am having sounds fire off periodically (every 700 ms). I want these sounds to play on another thread than the UI thread. Thus, I cannot use a dispatch timer
because the UI thread will be heavily used in the meantime while these sounds fire.
In looking at this problem, I made a backgroundworker
with a Thread.Sleep(700)
command. This works, but as one may expect it can take longer than 700 ms to fire off a sound. So sometimes I hear delays.
So I turn to you guys -- How can I get as close to a firing of a sound every 700 ms in a backgroundworker
or another thread? Is a Timer
a wise idea?
Here is some code to better illustrate:
private void RunBackgroundWorker()
{
backgroundWorker = new BackgroundWorker ();
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += new DoWorkEventHandler(StartSounds);
backgroundWorker.RunWorkerAsync();
}
public void StartSounds(object sender, EventArgs e)
{
for (currentsoundchoice = 0; currentsoundchoice <= max; currentsoundchoice ++)
{
if (backgroundWorker.CancellationPending == true)
{
backgroundWorker.CancelAsync();
currentsoundchoice = max + 1; //just to ensure it stops.
}
else
{
Time_Tick();
if (max == 12)
currentsoundchoice = -1; //repeats the loop when it reaches max.
}
}
}
void Time_Tick()
{
Thread.Sleep(700);
FrameworkDispatcher.Update();
switch (sounds)
case 0: //code
break;
// ETC, So forth.......
}
I heard that using a Timer is also a good way to go about this, but is it possible to run a timer in a backgroundworker, and if so, how would it be structured? More importantly, would it allow me to get as close to the 700 ms firing time I desire without any audible delays?
Thank you.
Upvotes: 0
Views: 402
Reputation: 178630
BackgroundWorker
is the wrong choice here. It is designed to allow you to perform expensive work on a background thread and then synchronize the results back to the UI. You do not need any synchronization. Moreover, you need the work to occur at a regular interval - not as a one-off task.
A Timer
would be much more suited. It would allow you to run your logic every 700ms and to remove the nasty Thread.Sleep()
call you have in your current code. The Timer
will use a background thread just like BackgroundWorker
does.
Note, however, that it can only guarantee that it won't run before 700ms has elapsed. If you're absolutely hammering the device, for example, it may struggle to run your code on a regular interval and you may notice lag.
Upvotes: 1