从Async中检索响应字符串。网络请求

时间:2013-12-27 17:45:59

标签: c# .net multithreading compact-framework

我一直在研究这几天在互联网上寻找答案,对于紧凑的框架似乎没有一个好的。

我需要做的是从GetResponseCallBack获取响应字符串并将其传递回主线程以更新GUI。

有没有人在紧凑的框架中完成此操作?我使用的是.NET 3.5

以下是我的两个回调

private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    // End the operation
    Stream postStream = request.EndGetRequestStream(asynchronousResult);


    string postData = "&location=funville";

    // Convert the string into a byte array. 
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);

    // Write to the request stream.
    postStream.Write(byteArray, 0, postData.Length);
    postStream.Close();

    // Start the asynchronous operation to get the response
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    // End the operation
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
    Stream streamResponse = response.GetResponseStream();
    StreamReader streamRead = new StreamReader(streamResponse);
    string responseString = streamRead.ReadToEnd();
    // Close the stream object
    streamResponse.Close();
    streamRead.Close();

    // Release the HttpWebResponse
    response.Close();
    allDone.Set();
}

以下是我用来创建请求的代码

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.SendChunked = true;
request.ContentType = "application/x-www-form-urlencoded";

// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";

// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

// Keep the main thread from continuing while the asynchronous 
// operation completes. A real world application 
// could do something useful such as updating its user interface. 
allDone.WaitOne();

它主要只是来自MSDN的默认代码,我得到了正确的响应数据,因为我有一个MessageBox弹出回调中的响应字符串我只需要一些方向将其传递给主线程。

1 个答案:

答案 0 :(得分:2)

您已经拥有使用allDone事件通知主线程的代码。您可以将结果放在主线程可见的变量中,然后调用allDone.Set。当主线程看到事件已设置时,它可以从该变量中获取结果。

您的主要问题似乎是如何确定结果是否准备就绪。这是一个更难的问题,取决于主线程在做什么。如果主线程正在等待用户输入,那么您可以用event-based asynchronous pattern替换事件和全局变量。关键是使用类似Control.Invoke的内容将事件封送到UI线程。

如果您的主线程正在执行其他操作,则必须不时轮询allDone事件。类似的东西:

while (!allDone.WaitOne(0))
{
    // do stuff
}
// get and process result

或者:

while (true)
{
    if (allDone.WaitOne(0))
    {
        // get and process result
    }
}