Android平臺有一個Handler類,用於對消息或事件進行排隊,以便稍後或在不同的線程上運行。我在環視MSDN文檔和網絡上的Windows Phone 7平臺上可用的一些等效的API,但沒有找到任何東西。Silverlight/Windows Phone 7相當於android.os.Handler
我可以自己實施該服務,但不願意重新發明輪子。有沒有人找到過類似的東西或者有什麼好的想法?
乾杯, 阿拉斯代爾。
Android平臺有一個Handler類,用於對消息或事件進行排隊,以便稍後或在不同的線程上運行。我在環視MSDN文檔和網絡上的Windows Phone 7平臺上可用的一些等效的API,但沒有找到任何東西。Silverlight/Windows Phone 7相當於android.os.Handler
我可以自己實施該服務,但不願意重新發明輪子。有沒有人找到過類似的東西或者有什麼好的想法?
乾杯, 阿拉斯代爾。
以下是代碼的要點。您一定需要進行更改。希望能幫助到你。
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類的線程嗎?
您可以使用ThreadPool.QueueUserWorkItem在不同的線程上運行,或使用ThreadPool.RegisterWaitForSingleObject註冊委託以等待超時並稍後運行。
感謝@Vivek我知道這些API,並一直在使用這些方法來實現所需的行爲。關於使用Handler實現的好處是您可以免費排隊消息/動作,並且可以根據需要取消隊列。 – ajmccall
好的,我明白了。誠然,你有能力安排和傳遞消息Android的情況下。我相信你已經考慮過了 - 在RegisterWaitForSingleObject中傳遞一個字典項目隊列。可能會做類似的事情嗎? –
您還需要查看Dispatcher.BeginInvoke以在主線程上執行代碼(以顯示計算結果,網絡調用等)。 – wilbur4321
我不需要提供完整的代碼示例來回答我的問題。建議ThreadPool.RegisterWaitForSingleObject方法調用就足夠了。不管怎麼說,還是要謝謝你。 – ajmccall
@ajmccall,我一定誤會了。由於我在前面的回覆中提到過'ThreadPool.RegisterWaitForSingleObject',我以爲你在尋找更多的細節。無論如何,很高興這有助於。 –
我不認爲這個答案是線程安全的。 Queue對象在線程間共享,但文檔指出Queue的實例不是自動線程安全的:http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx此外,此實現與Handler有點不同,因爲在這種情況下,它一直等待5秒鐘,Handler更靈活,它不需要每個消息在處理之前等待相同的時間。 – satur9nine