Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8249041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T23:24:01+00:00 2026-06-07T23:24:01+00:00

Im trying to convert the response from the webclient to Json, but it’s trying

  • 0

Im trying to convert the response from the webclient to Json, but it’s trying to create the JSON object before it is done downloaing it from the server.
Is there a “nice” way to for me to wait for WebOpenReadCompleted to be executed?

Have to mention that this is a WP7 app, so everything is Async

public class Client
{

    public String _url;
    private String _response;
    private WebClient _web;

    private JObject jsonsobject;
    private Boolean blockingCall;


    private Client(String url)
    {
        _web = new WebClient();
        _url = url;
    }

    public JObject Login(String username, String password)
    {
        String uriUsername = HttpUtility.UrlEncode(username);
        String uriPassword = HttpUtility.UrlEncode(password);

        Connect(_url + "/data.php?req=Login&username=" + uriUsername + "&password=" + uriPassword + "");
        jsonsobject = new JObject(_response); 
        return jsonsobject;
    }

    public JObject GetUserInfo()
    {

        Connect(_url + "/data.php?req=GetUserInfo");
        jsonsobject = new JObject(_response); 
        return jsonsobject;
    }

    public JObject Logout()
    {

        Connect(_url + "/data.php?req=Logout");
        jsonsobject = new JObject(_response); 
        return jsonsobject;
    }

    private void Connect(String url)
    {

        _web.Headers["Accept"] = "application/json";
        _web.OpenReadCompleted += new OpenReadCompletedEventHandler(WebOpenReadCompleted);
        _web.OpenReadAsync(new Uri(url));
    }

    private void WebOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        if (e.Error != null || e.Cancelled)
        {
            MessageBox.Show("Error:" + e.Error.Message);
            _response = "";
        } 
        else
        {
            using (var reader = new StreamReader(e.Result))
            {
                _response = reader.ReadToEnd();
            }    
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T23:24:02+00:00Added an answer on June 7, 2026 at 11:24 pm

    You can use an EventWaitHandle to nicely block until the async read is complete. I had a similar requirement for downloading files with WebClient. My solution was to subclass WebClient. Full source is below. Specifically, DownloadFileWithEvents blocks nicely until the async download completes.

    It should be pretty straightforward to modify the class for your purpose.

    public class MyWebClient : WebClient, IDisposable
    {
        public int Timeout { get; set; }
        public int TimeUntilFirstByte { get; set; }
        public int TimeBetweenProgressChanges { get; set; }
    
        public long PreviousBytesReceived { get; private set; }
        public long BytesNotNotified { get; private set; }
    
        public string Error { get; private set; }
        public bool HasError { get { return Error != null; } }
    
        private bool firstByteReceived = false;
        private bool success = true;
        private bool cancelDueToError = false;
    
        private EventWaitHandle asyncWait = new ManualResetEvent(false);
        private Timer abortTimer = null;
    
        const long ONE_MB = 1024 * 1024;
    
        public delegate void PerMbHandler(long totalMb);
    
        public event PerMbHandler NotifyMegabyteIncrement;
    
        public MyWebClient(int timeout = 60000, int timeUntilFirstByte = 30000, int timeBetweenProgressChanges = 15000)
        {
            this.Timeout = timeout;
            this.TimeUntilFirstByte = timeUntilFirstByte;
            this.TimeBetweenProgressChanges = timeBetweenProgressChanges;
    
            this.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(MyWebClient_DownloadFileCompleted);
            this.DownloadProgressChanged += new DownloadProgressChangedEventHandler(MyWebClient_DownloadProgressChanged);
    
            abortTimer = new Timer(AbortDownload, null, TimeUntilFirstByte, System.Threading.Timeout.Infinite);
        }
    
        protected void OnNotifyMegabyteIncrement(long totalMb)
        {
            if (NotifyMegabyteIncrement != null) NotifyMegabyteIncrement(totalMb);
        }
    
        void AbortDownload(object state)
        {
            cancelDueToError = true;
            this.CancelAsync();
            success = false;
            Error = firstByteReceived ? "Download aborted due to >" + TimeBetweenProgressChanges + "ms between progress change updates." : "No data was received in " + TimeUntilFirstByte + "ms";
            asyncWait.Set();
        }
    
        void MyWebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (cancelDueToError) return;
    
            long additionalBytesReceived = e.BytesReceived - PreviousBytesReceived;
            PreviousBytesReceived = e.BytesReceived;
            BytesNotNotified += additionalBytesReceived;
    
            if (BytesNotNotified > ONE_MB)
            {
                OnNotifyMegabyteIncrement(e.BytesReceived);
                BytesNotNotified = 0;
            }
            firstByteReceived = true;
            abortTimer.Change(TimeBetweenProgressChanges, System.Threading.Timeout.Infinite);
        }
    
        public bool DownloadFileWithEvents(string url, string outputPath)
        {
            asyncWait.Reset();
            Uri uri = new Uri(url);
            this.DownloadFileAsync(uri, outputPath);
            asyncWait.WaitOne();
    
            return success;
        }
    
        void MyWebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (cancelDueToError) return;
            asyncWait.Set();
        }
    
        protected override WebRequest GetWebRequest(Uri address)
        {            
            var result = base.GetWebRequest(address);
            result.Timeout = this.Timeout;
            return result;
        }
    
        void IDisposable.Dispose()
        {
            if (asyncWait != null) asyncWait.Dispose();
            if (abortTimer != null) abortTimer.Dispose();
    
            base.Dispose();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert a server side Ajax response script into a Django HttpResponse,
I need to convert a string to a JSON object that gets returned from
I am trying to get a response from my server using restful services, I
I'm trying to convert the following function from ASP to PHP: Function InvalidParam(response) InvalidParam
I am trying to parse the JSON response from Wordnik's API. This is built
I'm trying to read the response from a server using a socket and the
I'm having a huge problem trying to figure out a json response from a
I'm trying to send XML doc to server from client. But when server get
Trying to convert output from a rest_client GET to the characters that are represented
Trying to convert the following but am having difficulty. Can anyone see where I'm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.