欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

windows phone 中HttpWebRequest异步线程同步

程序员文章站 2022-04-12 08:39:34
public class RequestState     {        ...

public class RequestState
    {
        public HttpWebRequest request { get; set; }
        public HttpWebResponse response { get; set; }
        public Stream streamResponse { get; set; }
    }

    public class HttpHelper
    {
        public delegate void GetData(string text);

        public event GetData Data;

        public class HttpCallBackEvent
        {
            public HttpWebRequest request;
            public byte[] file;
            public string name;
            public string fileName;

        }


        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public Stream HttpGet(string url )
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
            request.Method = "GET";

            RequestState state = new RequestState();
            state.request = request;

            request.BeginGetResponse(webResponseCallack,state);
            allDone.Reset();    www.2cto.com
            allDone.WaitOne();

            return state.streamResponse;
        }

        private void webResponseCallack(IAsyncResult result)
        {
            try             {
                RequestState state = (RequestState)result.AsyncState;
                HttpWebRequest request = state.request;
                state.response = (HttpWebResponse)request.EndGetResponse(result);
                state.streamResponse = state.response.GetResponseStream();
               
            }
            catch             { }
            finally             {
                allDone.Set();
            }
        }


}


作者:修修