Windows Phone 8 - 等待 HttpWebRequest 在 Application_Closing 方法中完成

Windows Phone 8 - waiting for HttpWebRequest to finish in Application_Closing method

我的 Windows Phone 8 应用程序中有一个组件(我们称之为 RequestSender),它包含一个请求队列,以及一个线程(我们称之为 SenderThread),它读取队列(在出队时阻塞),并使用 HttpWebRequest 发送请求。

SenderThread 方法中的 HttpWebRequest 是以模拟同步调用的方式完成的,如下所示:

 _requestWaitHandle.Reset();
 IAsyncResult respResult = webReq.BeginGetResponse(GetResponseStreamCallback, null);
 _requestWaitHandle.Wait();
 HttpWebResponse response = webReq.EndGetResponse(respResult) as HttpWebResponse;

回调方法在这里做的唯一一件事是设置 _requestWaitHandle(顺便说一下,这是一个 ManualResetWaitHandleSlim)。

所有这一切工作正常,除了这种情况,当我在用户按下 "Back" 硬件按钮后关闭应用程序时尝试发送 "goodbye" 请求。

我尝试简单地将 "goodbye" 请求放入 Application_Closing 方法中,然后在 RequestSender 上调用 "Stop"。 Stop 方法会向线程发出它应该退出的信号(通过设置适当的标志),然后在线程上调用 Join()。

SenderThread 应该完成对 Web 请求的处理,检查 "stop" 标志,然后简单地退出。这就是理论。

实际上,"goodbye" 请求进入队列,开始处理,但 HttpWebRequest 只是挂在 BeginGetResponse 上,永远不会退出。可能是什么原因造成的?

在以下问题的其中一个答案中: 指出,"The HttpWebRequest use UI thread to process a request, don't ask me why."。这是真的?我怎样才能避免这种情况并简单地发出网络请求?我需要为此使用 HttpWebRequest 以外的东西吗?

我需要和你完全一样的东西,我测试了平台上的所有东西,但只有套接字才能完成工作。

如果您想试试套接字的运气 - 这里是 what I used (just delete the JSON-related stuff). And you'll also need this library

用法是这样的:

var http = new HttpSocketConnection();
var postBody = new HttpPostBodyBuilder.*Body();
// Here you set some parameters
using (var bodyStream = postBody.PrepareData()) {
    var req = new HttpMessage.Request(bodyStream, "POST");
    req.ContentLength = bodyStream.Length;
    req.ContentType = postBody.GetContentType();

    // send request
    var response = http.Send(url, req);
}

希望这对您有所帮助。 :)

P.S。代码远非完美,但它满足了我的需要,你知道那句老话:"If something's not broken, don't fix it"。 :)