0

I have two processes running on my UI thread. However, when I run the first, with BeginGetStream functionality, it enters the cycle and waits for its execution and returns the result when you are ready, but in the second run, through the BeginGetResponse functionality, this "die" there and the program does not continue and does not return me the value I want. Within these processes use the IasynResult.

I've tried:

  • Convert to a Task (Task.Run)

  • Allocate the process a new thread (Thread x = new Thread ())

  • Set the parameter ConfigureAwait (ConfigureAwait ( continueOnCapturedContext: false), ConfigureAwait (false));

  • Convert to asyncronos methods and apply the "await"

  • Use the AutoResetEvent to wait for the process to complete and do not proceed.

  • Placement thread to sleep (Thread.Sleep)

  • Use of Thread.Start, Thread.Join

  • etc....

I have essentially three functions(Function1,Function2 and Function3). Initially,I only use the Function2 and function3 and everything ok. Then, in anext order,where I do not want the UI thread lock,it blocks,and this time chamos the three functions I have, but the application blocks me when I make the request for BeginGetResponse in Function2.Not out there. (Putting the whole project in asynchronous is very costly,so this option will be the last.) I do not knowwhat elsecan I do...:( Some code example:


Function 1:

public void Function1()
             {

                  {           
HttpWebRequest requestHttp = (HttpWebRequest)HttpWebRequest.CreateHttp(new Uri(serverUrl, UriKind.Absolute));

                        string RString = string.Format("rftoken=123456789");
                        AutoResetEvent handler = new AutoResetEvent(false);
                        IAsyncResult TestResult= null;
                        try
                        {
                            requestHttp.BeginGetRequestStream(
                                (IAsyncResult result) =>
                                {
                                    TestResult= result;
                                    handler.Set();
                                }, requestHttp );

                            handler.WaitOne();

                        }
                        catch (Exception) { }

                        return Function2(TestResult, RString );
                    }               
                }

--------FUNCTION 2 ----------------------------------------------------------------------------------------

private Example Function2(IAsyncResult TestResult2, string RString2)

    try
    {
        HttpWebRequest request = (HttpWebRequest)TestResult2.AsyncState;
        Stream strm = request.EndGetRequestStream(TestResult2);
        StreamWriter writer = new StreamWriter(strm);
        writer.Write(RString2);
        writer.Dispose();
    }
    catch
    {}

    AutoResetEvent handler = new AutoResetEvent(false);
    IAsyncResult Async= null;

    try
    {
        requestHttp.BeginGetRequestStream(
            (IAsyncResult result) =>
            {
                Async= result;
                handler.Set();
            }, requestHttp );

        handler.WaitOne();

    }
    catch (Exception) { }

    return Function3(Async);
} 
}

------------FUNCTION 3 ---------------------------------------------------------------------------------------

   private Example Function3 (IAsyncResult Async3)

{....}

... I do not know what else to try ... Someone can help me.

Thank you.

fipcurren88
  • 701
  • 5
  • 26
  • You should not create an IAsyncResult by hand, you must propagate the generated ones by the Begin' End' functions. Also, if you are doing a handler.WaitOne(), why are you using async functions? you are blocking those threads... – Gusman Apr 15 '15 at 19:45
  • Hi, Thanks. Because I need the result of Function2 for invoke Function3 with the correct argument, Otherwise, the value passed by parameter is null, and the functionality I want is not performed in the function 3. – fipcurren88 Apr 16 '15 at 08:18
  • No, you didn't understood me, I mean, why use async methods when you are executing it synchronously? Instead of starting the request in a function, block that function and finish the download in other functuion just do the process synchronously and isolated on each function – Gusman Apr 16 '15 at 10:02
  • Hello, I tried to join the Function 1 and Function in the same function, and the problem still continued. I do not understand why this happens. This is called after some time, 5 minutes after the program is running. I just do not understand why to lock me in Function2 when I make the second call. This is because Funtion2 and function3 is called to start the application and everything is ok. The second time, when I call the Function1, Function2 and Funtion 3, stuck in Function2. I do not understand the problem. -- thank you – fipcurren88 Apr 16 '15 at 10:55
  • As I stated in my answer you cannot call twice to BeginGetRequestStream, so the handler is never set, so the application gets stuck – Gusman Apr 16 '15 at 12:44

2 Answers2

0

I think your UI thread block because you invoke handler.WaitOne(); in a synchronous method 'Function1` in the UI thread.

I think the solution is make all three method as async functions, and make method invoke your function1 to async method as well.

I assume you invoke the Function1 in a click event, and refresh the UI after get the result. Then the solution will looks like that:

UI Thread

async void Click(object sender, RoutedEventArgs e)
{
        var result = await Function1();
}

Function1, Function2, Function3

async Task<Result> Function1()
{
    var resp = await requestHttp.BeginGetRequestStream();
    return Function2(resp);
}

async Task<Result> Function2(Response response)
{
    var resp2 = await xxxxx();
    return Function3(resp2);
}

async Task<Result> Function(Type2 response)
{
    await xxxxx();
    //calculation
    return Result;
}
2power10
  • 1,259
  • 1
  • 11
  • 33
  • Hi, No, I not call de Function1 in a click event.There is a wide range of functions, which are called before this, however the problem is, when I make the BeginGetResponse in Function2. This is called after some time, 5 minutes after the program is running. I just do not understand why to lock me in Function2 when I make the second call. This is because Funtion2 and function3 is called to start the application and everything is ok. The second time, when I call the Function1, Function2 and Funtion 3, stuck in Function2. I do not understand the problem. -- thank you – fipcurren88 Apr 16 '15 at 11:03
0

Ok, so I understand you are using Silverlight framework which only has asynchronous methods.

You are using them wrong, your code must not block, you must "let the async flow" ;)

void DownloadUrl()
{
    HttpWebRequest requestHttp = (HttpWebRequest)HttpWebRequest.CreateHttp(new Uri(serverUrl, UriKind.Absolute));

    requestHttp.BeginGetRequestStream(SendRequestContent, requestHttp);
}

void SendRequestContent(IAsyncResult Result)
{
    string RString = string.Format("rftoken=123456789");
    HttpWebRequest req = (HttpWebRequest)Result.AsyncState;
    var reqStream = req.EndGetRequestStream(Result);
    using(StreamWriter writer = new StreamWriter(reqStream))
        writer.Write(RString);

    //And here you have again GetRequestStream, I suppose it's wrong and you want ResponseStream, you cannot instantiate twice the request stream...

    req.BeginGetResponse(GetResponse, req);
}

void GetResponse(IAsyncResult Result)
{

    var req = (HttpWebRequest)Result.AsyncState;

    var response = (HttpWebResponse)req.EndGetResponse(Result);

    string content = null;

    using(StreamWriter sw = new StreamWriter(response.GetResponseStream())
        content = sw.ReadToEnd();

    //And now you have the HTTP response in the "content" string, you can now finally use it. Beware you are outside the UI thread, if you must interact with it remember to use Invoke()
}
Gusman
  • 14,905
  • 2
  • 34
  • 50