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

  • Home
  • SEARCH
  • 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 6550237
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T12:11:30+00:00 2026-05-25T12:11:30+00:00

Summary: Is this even possible? unit test function on ui thread: – creates a

  • 0

Summary: Is this even possible?

unit test function on ui thread:
- creates a background thread
- starts the thread
- waits for it to complete (function does not exit until it completes!)

background thread:
- opens an http stream 
- reads a url from the web
- terminates

My suspicion: The framework asynchronously puts the result onto some internal message queue and thus the response callback will never be called until the ui thread’s stack unwinds and goes to some ui thread function to pump the stack.


The full story:

I am porting an app that requires creating a stream from various sources, one of them being from a simple http url. I am doing this on a background thread, and ideally I would like it to behave 100% synchronously, just block when needed (this is ok since it’s on a background thread).

But it seems the framework is a bit mickey mouse in that it assumes you will be doing the request on the ui thread and so it will shield the coder from having to create a background thread to do the asynch operation. But I may be missing something.

I have stumbled across the following article:
http://pieterderycke.wordpress.com/2011/05/23/adding-synchronous-methods-to-webrequest-on-windows-phone-7/,
which suggests a solution to make the http web request synchronous. But as it is implemented, I get a ProtocolViolationException. I have since made a modification to the code to use BeginGetResponse() instead of BeginGetRequestStream(), and this seems to no longer cause the exception.

But it seems that the background thread now blocks indefinitely. On my ui thread I loop, doing a Thread.Sleep(10) since I am in a unit test function, waiting for my callback to get called. Is it possible that the callback will not be called until unit test function returns and the ui thread has a chance to pump messages? If so, any way I can force it to pump so that I can continue where I left off in the unit test routine?

At the bottom of the article mentioned above, a comment is made “If you test your code, you will find that it deadlocks if you execute it on the UI thread.” but I am executing it on a background thread, so should be ok right?

The msdn docs only show you how to do asynch calls. And they also mention that “The BeginGetResponse method requires some synchronous setup tasks to complete” … “typically several seconds” … but “can take 60 seconds or more”. This sounds pretty bad to be executed on a ui thread.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx

Please help!

Here is my code:

using System.Net;
using System.Threading;
using System;
using System.IO;

namespace Blah
{
  // http://pieterderycke.wordpress.com/2011/05/23/adding-synchronous-methods-to-webrequest-on-windows-phone-7/
  // Creates synchronous web requests.
  // Must not be called on UI threads.

  public static class WebRequestExtensions
  {
    public static Stream GetRequestStream(this WebRequest request)
    {
      AutoResetEvent autoResetEvent = new AutoResetEvent(false);

      IAsyncResult asyncResult = null;
      {
        // http://stackoverflow.com/questions/253549/how-do-i-use-httpwebrequest-with-get-method

        if (request.Method == "GET")
        {
          asyncResult = request.BeginGetResponse(
           r => autoResetEvent.Set(), null);
        }
        else
        {
          asyncResult = request.BeginGetRequestStream(
           r => autoResetEvent.Set(), null);
        }
      }

      // Wait until the call is finished
      autoResetEvent.WaitOne();

      return request.EndGetRequestStream(asyncResult);
    }
  }
}

I’ve also recently stumbled across http://www.eggheadcafe.com/tutorials/aspnet/91f69224-3da5-4959-9901-c5c717c9b184/making-silverlight-emulate-synchronous-requests.aspx, but this exhibits the same problem. Seems that I don’t get my callback until the ui thread returns up the stack… I can smell some sort of a framework message queue there somewhere, am I correct?

Thanks

  • 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-05-25T12:11:31+00:00Added an answer on May 25, 2026 at 12:11 pm

    As HTTP response processing utilises the UI thread, blocking it will prevent the request from completing.

    Assuming you are using the Silverlight Unit Testing Framework bits, you can mark your test as [Asynchronous]:

    using System;
    using System.Net;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.Silverlight.Testing;
    
    [TestClass]
    public class WebRequestsTests : WorkItemTest
    {
        [TestMethod, Asynchronous]
        public void TestWebRequest()
        {
            var webRequest = WebRequest.CreateHttp("http://www.stackoverflow.com");
    
            webRequest.BeginGetResponse(result =>
            {
                EnqueueCallback(() =>
                {
                    WebResponse response = webRequest.EndGetResponse(result);
    
                    // process response 
    
                    TestComplete(); // async test complete 
                });
            }, null);
        }
    } 
    

    Alternatively, if you’re looking to use Rx (which I do, personally), I recently did a blog post on how to make Rx-based asynchronous tests cleaner when using the SL testing framework.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Executive Summary: When assertion errors are thrown in the threads, the unit test doesn't
I'm not even sure this is possible to do efficiently, but here's my problem:
Suppose I have this interface public interface IFoo { ///<summary> /// Foo method ///</summary>
Possible Duplicate: How do I fix this Perl code so that 1.1 + 2.2
I want this kind of result from these tables. I even can't figure out
I'm curious about this code snippet: public static class XNAExtensions { /// <summary> ///
i feel retarded for even asking this because its on the tip of my
I would like a summary of what exactly is thread safe in C++ both
I've added an ASP.net MVC validation summary and even when the page is first
Summary: How would I go about solving this problem? Hi there, I'm working on

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.