1

I am trying to implement a simple Windows 8 C# XAML application where there are two calls made to access single web service one from project to load and display data and other to display notification. Since there are two calls made for same web service I want that if one call is already made to the service the other call should wait and use the same response from the first call.

How can i achieve this kind of functionality? I have not added any code since there is no code that i have written for this. I am just trying to think first and then will I code.

Please let me know I can get some help for this kind of project structure?

9
  • Please don't stack your title with tags, it isn't necessary.
    – slugster
    Feb 12, 2013 at 11:21
  • Is the response content the same on both calls? Feb 12, 2013 at 11:23
  • @Alex: yes the response is same for both the calls. Feb 12, 2013 at 11:39
  • So, why don't you persist the information from the first call and reuse it? Is the second call really necessary? Does it contain any different metadata which you need to use? Feb 12, 2013 at 11:44
  • @Alex: That a good idea. But I am talking about a situation where both the calls are almost one after the other and the data from the first call has still not been received? Feb 12, 2013 at 11:46

3 Answers 3

1

You can do this by caching the Task that's currently downloading and not starting the download again if there is a cached Task:

private volatile Task<string> m_cachedWebServiceTask;

async Task<string> AccessWebServiceAsync()
{
    var task = m_cachedWebServiceTask;

    if (task == null)
        task = m_cachedWebServiceTask = DownloadFromWebServiceAsync();

    try
    {
        return await task;
    }
    finally
    {
        m_cachedWebServiceTask = null;
    }
}

Note that this code has a race condition: if you call AccessWebServiceAsync() twice at the same time, there is a small chance DownloadFromWebServiceAsync() will be called twice too. But since this in only an optimization, I think that shouldn't be a problem. If it is a problem for you, you would need to guard the access to the field by a lock.

0

As I had the feeling that this problem needs further attention and it's solution could still be optimized, I decided to post another approach. The OP is mostly a problem about leveraging the following 3 scopes of requirements: user experience within the application, the application's internal requirements and the web service's loading with multiple requests.

  1. The application needs to make an initial request to load the data.
  2. When he asks for it, the user expects to get the results with the latest updates.
  3. On the other side, it makes no initiate a large series of calls to the web service within a very short moment of time.

So, managing what happens in this very short moment of time it's actually the solution to the problem.

On the client side, the Service1Client class:

public partial class Service1Client
{
    // default time buffer value
    int _timeBuffer = 100;

    // a time buffer used for returning the same response  
    public int TimeBuffer
    {
        get { return _timeBuffer; }
        set { _timeBuffer = value; }
    }
    // the start and end time of the web service request
    static DateTime _start, _end;

    // a volatile static variable to store the response in the buffering time
    volatile static string _response;

    // used for blocking other threads until the current thread finishes it's job
    object _locker = new object();

    public async Task<string> GetResponseData()
    {
        return await Task.Factory.StartNew<string>(() =>
        {
            lock (_locker)
            {
                if (DateTime.Now >= _end.AddMilliseconds(TimeBuffer))
                {
                    _start = DateTime.Now;
                    var async = GetDataAsync();
                    _response = async.Result;
                    _end = DateTime.Now;
                }
            }
            return _response;
        });
    }
}

The console application used for testing:

class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            var client = new ServiceReference1.Service1Client();
            client.TimeBuffer = 150;
            Console.WriteLine(client.GetResponseData().Result);
            if (Console.ReadKey().Key == ConsoleKey.Enter)
                break;
        }
    }
}

As a remark, note that, for the reason of a clear sample, I decided to change the returned type of the GetDate WCF service's method from DateTime to string.

[ServiceContract]
public interface IService1
{
    [OperationContract]
    string GetData();
}

public class Service1 : IService1
{
    public string GetData()
    {
        System.Threading.Thread.Sleep(5000);
        return DateTime.Now.ToString();
    }
}
1
  • The point of async-await is to not block threads. And this solution doesn't block the main thread, but it does block one or more ThreadPool threads while the operation is executing. That's not a good approach.
    – svick
    Feb 13, 2013 at 11:20
-1

For your scenario, a feasible idea would be to extend the service class.

The IService1 interface definition:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    DateTime GetData();
}

The Service1 class definition:

public class Service1 : IService1
{
    public DateTime GetData()
    {
        System.Threading.Thread.Sleep(5000);
        return DateTime.Now;
    }
}

On the client side, extend the Service1Client class definition and add a new method:

public partial class Service1Client
{
    static bool _isOpen;

    static DateTime? _cachedResponse;
    object _locker = new object();

    public DateTime GetResponseData()
    {
        if (!_isOpen)
        {
            if (!_cachedResponse.HasValue)
            {
                lock (_locker)
                {
                    _isOpen = true;
                    _cachedResponse = GetData();
                    _isOpen = false;
                }
                return _cachedResponse.Value;
            }
            else
            {
                Task.Factory.StartNew<DateTime>(() =>
                {
                    lock (_locker)
                    {
                        _isOpen = true;
                        _cachedResponse = GetData();
                        _isOpen = false;
                    }
                    return _cachedResponse.Value;
                });
            }
        }
        return _cachedResponse.Value;
    }
}

Test it:

class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            var client = new ServiceReference1.Service1Client();
            Console.WriteLine(client.GetResponseData());
            if (Console.ReadKey().Key == ConsoleKey.Enter)
                break;
        }
    }
}
5
  • This won't work, you return from GetResponseData() before the result can be set (and the value returned from the Task doesn't have any effect). Also, the question was tagged async-await and that's what you should always use when accessing external services in Win 8 apps.
    – svick
    Feb 12, 2013 at 17:47
  • @svick, this woks in my tests. Feb 12, 2013 at 18:12
  • They way you're written it, it can't work. And when I test your code, it actually doesn't work (it prints out 1.1.0001 0:00:00 for me).
    – svick
    Feb 12, 2013 at 18:45
  • You are right, I've updated the implementation. In the original answer I was focused on recurrent calls, I was not giving attention to the first call. Also, if you want to test it again, make sure that the WCF service is available. Feb 12, 2013 at 19:48
  • So, if the value was retrieved previously, you start retrieving it again, but return the old value? Why? Also, this still doesn't use async-await, so it's not the right way to do it in a Windows 8 app.
    – svick
    Feb 12, 2013 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.