0

What is the fastest and optimized way to load asynchronous results from various sources in web services?

Dictionary<string, int> readySources = GetReadyHotelSources(member);

        eventFlag = new AutoResetEvent[readySources.Count];
        int maxTimeOut = 0;
        int i = 0;
        foreach (KeyValuePair<string, int> activeSource in readySources)
        {
            maxTimeOut = (int)activeSource.Value > maxTimeOut ? (int)activeSource.Value : maxTimeOut;
            i++;
        }
        int j = 0;            
        foreach (KeyValuePair<string, WaitCallback> deThread in listOfThreads)
        {
            if (readySources.ContainsKey(deThread.Key))
            {
                ThreadPool.QueueUserWorkItem(deThread.Value, j);
                eventFlag[j] = new AutoResetEvent(false);
                j++;                    
            }
        }

        if (j != 0)
        {
            if (!WaitHandle.WaitAll(eventFlag, new TimeSpan(0, 0, maxTimeOut), true))
            {
                //TODO: audit which thread is timed out                
            }
        }          
        // combined sources    
        result = CombineHotelSources();

Now i want to move this code in async mode in web services.

Rohit
  • 300
  • 2
  • 14
  • If those various sources are CPU-bound calculational tasks, there's no point in doing them in parallel on the server side. That might greatly impact the scalability. If those sources are IO/network-bound, this may help: http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4 – noseratio Feb 17 '14 at 12:08
  • Yes, these are external sources over the network which we are hitting. – Rohit Feb 17 '14 at 12:36

1 Answers1

0

Use asynchronous Task-based API and async/await, as described here:

Using Asynchronous Methods in ASP.NET MVC 4.

Avoid wrapping a synchronous call with await Task.Run(), here's an example of what I mean. Normally you don't need to create new threads or explicitly use pool threads on the server side. You can call your WCF services asynchronously with Task.Factory.FromAsync, like this.

Community
  • 1
  • 1
noseratio
  • 59,932
  • 34
  • 208
  • 486