Serving Multiple Asynchronous HTTP Requests in Silverlight Serially

Due to the asynchronous HTTP access via WebClient or HttpWebRequest in Silverlight 4, when I want to do multiple HTTP messages / messages in turn, I find that I am writing code that looks like this:

doFirstGet(someParams, () =>   
  {
    doSecondGet(someParams, () =>
      {
        doThirdGet(...
      }   
  });

Or something similar. I would end up nesting subsequent calls in callbacks that are usually made using lambdas. Even if I break things down into actions or individual methods, it's still hard to read.

Does anyone have a clean solution to simultaneously execute multiple HTTP requests in SL 4?

I do not need code that actually removes all this in order to be synchronous, but I need the requests to be executed sequentially, so each request must be effectively synchronous.

+3
3

: -

Runner - 1
Runner - 2

, , , . , dll zip .

, 2 , , . : -

void StuffToDo()
{
    doFirstGet(someParams);
    doSecondGet(someParams);
    doThirdGet(...);
}

- "do", AsyncOperation. , , : -

void doFirst(someParams, Action callback)
{
    SomeAsyncObj thing = new SomeAsyncObj();
    thing.OnCompleted += (s, args) { callback() };
    thing.DoSomethingAsync();
} 

: -

AsyncOperation doFirst(someParams)
{
    return (completed) =>
    {
        SomeAsyncObj thing = new SomeAsyncObj();
        thing.OnCompleted += (s, args) =>
        {
            try
            {
                completed(null);
            }
            catch (Exception err)
            {
                completed(err);
            }
        };
        thing.DoSomethingAsync(source);
    };
}

- : -

IEnumerable<AsyncOperation> StuffToDo()
{
    yield return doFirstGet(someParams);
    // Do some other synchronous stuff here, this code won't run until doFirstGet has completed.
    yield return doSecondGet(someParams);
    // Do some other synchronous stuff here, this code won't run until doSecondGethas completed.
    yield return doThirdGet(...);
    // Do some final synchronous stuff here, this code won't run until doThirdGethas completed.

}

, StuffToDo : -

StuffToDo().Run((err) =>
{
   // report any error in err sensibly
});
+2

. , .

.

+1
  • Encapsulate each request in a class
  • Create a collection or array of queries
  • Iterate through the collection and processing of each request.
+1
source

Source: https://habr.com/ru/post/1790095/


All Articles