Tag Archives: Await

Async/Await Snipped: Ensure one-time execution

Think if you have some initialization code that you want to execute only once. Multiple threads could call in. Your code uses async and await keywords and you want to be able to await until it completes…

        Task _workerTask;

        object _workerSyncRoot = new object();

        async Task EnsureWorkerDoneAsync()
        {
            // ensure that the worker is executed only once
            lock (_workerSyncRoot)
                if (_workerTask == null)
                    _workerTask = WorkerAsync();
            
            // await the worker, if it has not
            if (_workerTask.Status != TaskStatus.RanToCompletion)
                await _workerTask;
        }
Advertisements
Tagged , , ,

Async/Await Snipped: Avoid multiple calls by using delays

When you work with async and await keywords in C#. You sometimes want to avoid unnecessary calls, that are caused by multi-threading. Here is a simple snipped that works fine…

Scenario: Last Wins

        Task _delayTask;

        async void StartWithDelay()
        {
            // keep a local copy and a member copy of the task
            Task delayTask = _delayTask = Task.Delay(1000);

            // await the delay
            await delayTask;

            // is it still the same task (or is there a new one)
            if(delayTask == _delayTask) 
            {
                // do your work here...
            }
        }
Tagged , , ,

Mocking and Unit Testing in Windows Store Apps

In Windows Store Apps most of the mocking frameworks out there cannot be used. The main reason is because Reflection is not available, another important point is that app.config is also not available and therefore type configuration cannot be placed there. So you can start by using a simple and very basic implementation.

Sample Mocking Structure

design

  • Model and ModelMock are deriving from IModel interface
  • The Model is returning real data
  • The ModelMock is returning mock data
  • The RuntimeActivator can create a Model instance and is returning either the Model or the Mock in dependance to the ModelType property.

Model Implementation

Model is just having one method that is returning the “real” data

    public class Model : IModel
    {
        public async Task<List<Entity>> GetData()
        {
            // simulate real data retrieval delay
            await Task.Delay(TimeSpan.FromSeconds(2));

            return new List<Entity>() 
            { 
                new Entity(){ Title = "real data1" }, 
                new Entity(){ Title = "real data2" } 
            };
        }
    }

ModelMock Implementation

The ModelMock is returning mock data. By using a compiler switch the Mock class will be available only in debug builds.

// mocks should be available only in debug releases
#if DEBUG
    public class ModelMock : IModel
    {
        public async Task<List<Entity>> GetData()
        {
            // simulate mock data retrieval delay
            await Task.Delay(TimeSpan.FromSeconds(2));
            return new List<Entity>() 
            { 
                new Entity(){ Title = "mock data1" }, 
                new Entity(){ Title = "mock data2" } 
            };
        }
    }
#endif
#endif

RuntimeActivator Implemenation

The RuntimeActivator is containing the type information and can create your instances. You can change your runtime configuration in the static constructor. Additionally Unit Tests are able to change it because the Type property accessor should be set to public. So if you want to switch from mock to integrative you can just comment and uncomment the lines as you want. You can do more structuring here like you want and need.

    public static class RuntimeActivator
    {
        static RuntimeActivator()
        {
            //ModelType = typeof(Models.Model);
            ModelType = typeof(Models.Mocks.ModelMock);
        }

        public static Type ModelType { get; set; }

        public static IModel CreateModel()
        {
            return (IModel)Activator.CreateInstance(RuntimeActivator.ModelType);
        }
    }

ViewModel Implemenation

The ViewModel is creating a Model instance and retrieving data from the model (real or mock).

   public class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            ViewData = new ObservableCollection<Entity>();
        }

        public async void Initialize()
        {
            var model = RuntimeActivator.CreateModel();

            Loading = true;
            try
            {
                ViewData.Clear();

                var result = await model.GetData();
                foreach (var item in result)
                {
                    ViewData.Add(item);
                }
            }
            finally
            {
                Loading = false;
            }
        }

        public ObservableCollection<Entity> ViewData { get; private set; }
        ...

IntegrativeTests Implemenation

The IntegrativeTests class is an illustrative sample containing a Unit Test to work against real data Рintegrative test. During test initialization model types can be configured.

    [TestClass]
    public class IntegrativeTests
    {
        [TestInitialize]
        public void Initialize()
        {
            // enable integrative real model
            RuntimeActivator.ModelType = typeof(Models.Model);
        }

        [TestMethod]
        public void ModelTest1()
        {
            var model = RuntimeActivator.CreateModel();
            var task = model.GetData();
            task.Wait();
            Assert.IsTrue(task.Result.Count() > 0);
        }
    }

View Sample

The following is a screenshot of the MockSample application. It could be a good starting point for you. In there is a basic MVVM implementation with Mock, Unit Test and View containing data binding. Asynchronous methods with async and await and a ProgressRing control is displayed to show status information.
MockSample Application Screenshot

Download Sample

You can download the fully working sample from here…
http://dl.dropbox.com/u/40751518/CodeSamples/MockSample.zip

Tagged , , , ,