為 Windows Phone 7 的 WebRequest 增加同步方法
我真的很喜歡開發 Windows Phone 7 程序。像 Visual Studio 和 Blend 都是優良的工具,而 Silverlight 和 XNA 是很好的框架。只能有一個很大的煩惱,就是 WebRequest 不支持同步的方法調用。雖然我知道不應該在 UI 線程上做業務處理,但我不喜歡微軟限定的這么死,作為一名開發人員,我寧愿自己作出這一選擇。
我已經創建了2個簡單的擴展方法添加到WebRequest的同步行為:
public static class WebRequestExtensions { public static WebResponse GetResponse(this WebRequest request) { AutoResetEvent autoResetEvent = new AutoResetEvent(false); IAsyncResult asyncResult = request.BeginGetResponse(r => autoResetEvent.Set(), null); // Wait until the call is finished autoResetEvent.WaitOne(); return request.EndGetResponse(asyncResult); } public static Stream GetRequestStream(this WebRequest request) { AutoResetEvent autoResetEvent = new AutoResetEvent(false); IAsyncResult asyncResult = request.BeginGetRequestStream(r => autoResetEvent.Set(), null); // Wait until the call is finished autoResetEvent.WaitOne(); return request.EndGetRequestStream(asyncResult); } }
請注意:使用 AutoResetEvent 會導致一些性能方面的損耗,因此上述代碼運行起來其一個真正的同步方法實現要低效。
注意2:我知道你可以從一個 IAsyncResult 對象獲取一個 WaitHandle,但這在 WP7 上是不可能的。
本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!