Silverlight/Windows Phone 7 Equivalent of android.os.Handler
The Android platform has a Handler clas开发者_如何学Pythons for queueing messages or events to be run at a later stage or on a different thread. I was looking around the MSDN docs and the net for some equivalent API available on the the Windows Phone 7 platform but did not find anything.
I could implement that service myself but would hate to reinvent the wheel. Has anyone had found something similar or have any bright ideas?
Cheers, Alasdair.
Here is the gist of the code. You will definitely need to make changes. Hope it helps.
private static Queue<Dictionary<string, string>> messages;
....
{
...
AutoResetEvent ev = new AutoResetEvent(false);
...
Dictionary<string, string> msg1 = new Dictionary<string, string>();
msg1.Add("Id", "1");
msg1.Add("Fetch", "Song1");
Dictionary<string, string> msg2 = new Dictionary<string, string>();
msg2.Add("Id", "2");
msg2.Add("Fetch", "Song2");
messages.Enqueue(msg1);
messages.Enqueue(msg2);
ThreadPool.RegisterWaitForSingleObject(
ev,
new WaitOrTimerCallback(WaitProc),
messages,
5000,
false
);
// The main thread waits 10 seconds, to demonstrate the
// time-outs on the queued thread, and then signals.
Thread.Sleep(10000);
...
}
private static void WaitProc(object state, bool timedOut)
{
// The state object must be cast to the correct type, because the
// signature of the WaitOrTimerCallback delegate specifies type
// Object.
Queue<Dictionary<string, string>> dict = (Queue<Dictionary<string, string>>)state;
string cause = "TIMED OUT";
if (!timedOut)
{
cause = "SIGNALED";
//signaled to return. return without doing any work
return;
}
// timed out. now do the work
Dictionary<string, string> s1 = dict.Dequeue();
}
`
Not sure if you are looking for a service to execute something in the background or something on a thread. Have you looked at ThreadPool class for threading?
You can use ThreadPool.QueueUserWorkItem to run on a different thread or use ThreadPool.RegisterWaitForSingleObject to register a delegate to wait for a timeout and run later.
精彩评论