windows phone 中HttpWebRequest异步线程同步

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();
            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();
            }
        }
posted @ 2012-07-11 09:48  张巍的博客  阅读(815)  评论(0编辑  收藏  举报