为什么我的2个AsyncCallbacks表现得像同步调用

时间:2012-06-14 00:53:17

标签: c#

我相信我已经正确地设置了它。有人可以看到这个代码有什么问题。它应该执行IAsyncResult asyncResult1然后立即移动到IAsyncResult asyncResult2吗?行为是它调用asyncResult1(调用ExecuteAsyncRequest),其余服务保持一点,然后返回它,然后调用下一个。它不应该只是BeginGetResponse然后继续下一个电话吗?

WCF Rest Service网络方法是:

 public Stream CheckOutForMaster(Stream clientServerXmlStream)
    {
       //Logic 1: Checks if it's between a set 30 second window.
       //Logic 2: Processes more logic
       //Logic 3: Holding pattern until the 30 second window is complete. Thus allowing multiple calls to be made via other connections.
       //Logic 4: Once 30 second window is complete. All connections have saved their  data to a database and each connection will retrieve all data from all connects.
    }

客户端测试代码:

[TestClass]
public class sccTests
{
    public static ManualResetEvent allDone = new ManualResetEvent(false);
    const int BUFFER_SIZE = 1024;
    const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
    List<XDocument> asyncClientServers;

    [TestMethod]
    public void CheckoutForMaster_OneClientServer_ReturnsAllMasterStatus()
    {
        string urlTest = CombineWithSccBaseUrl("/v1/clientservers/checkout");
        ...
        IAsyncResult asyncResult1 = ExecuteAsyncRequest(urlTest, xmlPayloadAllMaster);
        IAsyncResult asyncResult2 = ExecuteAsyncRequest(urlTest, xmlPayloadAllWait);
    }

    private IAsyncResult ExecuteAsyncRequest(string url, string payload)
    {
        try
        {

            byte[] bytes = Encoding.UTF8.GetBytes(payload);

            Uri uri = new Uri(url);
            // Create a HttpWebrequest object to the desired URL.
            HttpWebRequest myHttpWebRequest1 = (HttpWebRequest)WebRequest.Create(uri);
            myHttpWebRequest1.Method = "POST";
            myHttpWebRequest1.CachePolicy = new RequestCachePolicy(       RequestCacheLevel.NoCacheNoStore);
            myHttpWebRequest1.ContentLength = bytes.Length;
            myHttpWebRequest1.ContentType = "application/xml;charset=UTF-8";
            myHttpWebRequest1.Timeout = 105000;

            using (Stream putStream = myHttpWebRequest1.GetRequestStream())
            {
                putStream.Write(bytes, 0, bytes.Length);
            }

            // Create an instance of the RequestState and assign the previous myHttpWebRequest1
            // object to it's request field.  
            RequestState myRequestState = new RequestState();
            myRequestState.request = myHttpWebRequest1;

            // Start the asynchronous request.
            IAsyncResult result = myHttpWebRequest1.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
        }
        catch (WebException e)
        {
            string t = e.Message;
        }
        catch (Exception e)
        {
            string t = e.Message;
        }

        return null;

    }


    private void RespCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            // State of request is asynchronous.
            RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
            HttpWebRequest myHttpWebRequest2 = myRequestState.request;
            myRequestState.response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asynchronousResult);

            // Read the response into a Stream object.
            Stream responseStream = myRequestState.response.GetResponseStream();
            myRequestState.streamResponse = responseStream;

            if(myRequestState.response != null && myRequestState.response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(myRequestState.response.GetResponseStream(), Encoding.GetEncoding(1251));
                XDocument xResult = XDocument.Load(reader);
                asyncClientServers.Add(xResult);
            }
        }
        catch (WebException e)
        {
            // Need to handle the exception
        }
    }

 }

2 个答案:

答案 0 :(得分:1)

这看起来很可疑:

using (Stream putStream = myHttpWebRequest1.GetRequestStream())
{
    putStream.Write(bytes, 0, bytes.Length);
}
// ... etc
IAsyncResult result = myHttpWebRequest1.BeginGetResponse(
                      new AsyncCallback(RespCallback), myRequestState);

在调用BeginGetResponse()

之前,您似乎已经完成并完成了请求

答案 1 :(得分:1)

GetRequestStream的文档说:

  

您的应用程序不能为特定请求混合使用同步和异步方法。如果调用GetRequestStream方法,则必须使用GetResponse方法来检索响应。

如果您尝试混合使用同步方法,并没有说明会发生什么,但看到这样做会产生意外结果,您可能希望使用BeginGetRequestStream