C# HttpWebRequest.BeginGetResponse不工作。测试被卡住了

C# HttpWebRequest.BeginGetResponse不工作。测试被卡住了,c#,testing,windows-phone-8,C#,Testing,Windows Phone 8,我一直在尝试使用HttpWebRequest.BeginGetResponse,但它在CountdownEvent后被卡住。调用Wait。使用HttpClient,我没有遇到这个问题 private static CountdownEvent latch; [TestMethod] public void Test001() { latch = new CountdownEvent(1); HttpWebRequest requ

我一直在尝试使用HttpWebRequest.BeginGetResponse,但它在CountdownEvent后被卡住。调用Wait。使用HttpClient,我没有遇到这个问题

    private static CountdownEvent latch;

    [TestMethod]
    public void Test001()
    {
        latch = new CountdownEvent(1);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
        request.BeginGetResponse(new AsyncCallback(Finish), request);

        latch.Wait();
    }

    private void Finish(IAsyncResult result)
    {
        Debug.WriteLine("FINISH");
        latch.Signal();
    }

问题很可能来自HttpWebRequest.BeginGetResponse。。。需要UI线程在某个点不同步。我不知道为什么会这样,但事实就是这样

在您的例子中,Test001方法很可能是在UI线程中调用的。在门闩上,等等;它阻塞线程,因此请求实际上无法发出,并且永远不会完成


如果您可以在非UI线程上调用Test001方法,它应该可以工作。我不知道单元测试框架是如何工作的,除了这个,我帮不了你太多的忙。

你能试试这个吗

[TestMethod]
public async Task Test001()
{
    latch = new CountdownEvent(1);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
    request.BeginGetResponse(new AsyncCallback(Finish), request);

   await latch;
}

这个Test001方法是在UI线程中调用的吗?如果是,请打开闩锁。等待;行阻塞了UI线程,这就是问题所在。我不是很确定。老实说,我对Windows开发+这个silverlight单元测试框架非常陌生