【发布时间】:2011-06-22 15:44:45
【问题描述】:
Android 平台有一个 Handler 类,用于将消息或事件排队,以便在稍后阶段或在不同的线程上运行。我在 MSDN 文档和网络上寻找 Windows Phone 7 平台上可用的一些等效 API,但没有找到任何东西。
我可以自己实现该服务,但不愿意重新发明轮子。有没有人发现类似的东西或有什么好主意?
干杯, 阿拉斯代尔。
【问题讨论】:
标签: android windows-phone-7 message-queue
Android 平台有一个 Handler 类,用于将消息或事件排队,以便在稍后阶段或在不同的线程上运行。我在 MSDN 文档和网络上寻找 Windows Phone 7 平台上可用的一些等效 API,但没有找到任何东西。
我可以自己实现该服务,但不愿意重新发明轮子。有没有人发现类似的东西或有什么好主意?
干杯, 阿拉斯代尔。
【问题讨论】:
标签: android windows-phone-7 message-queue
这里是代码的要点。你肯定需要做出改变。希望对您有所帮助。
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();
}
`
【讨论】:
ThreadPool.RegisterWaitForSingleObject,我认为您正在寻找更多详细信息。无论如何,很高兴这有帮助。
不确定您是在寻找在后台执行某事还是在线程上执行某事的服务。你看过ThreadPool 类的线程吗?
您可以使用ThreadPool.QueueUserWorkItem 在不同的线程上运行或使用 ThreadPool.RegisterWaitForSingleObject 注册一个委托以等待超时并稍后运行。
【讨论】: