Tuesday, June 20, 2017

How to initialize instances asyncronously

Here is another problem I've been thinking about quite a while, before found a solution I like.
async/await keywords revolutionized the writing of asynchronous code in C#. It is as simple as marking a method with async keyword and using await in it to wait for asynchronous operations to complete in non-blocking manner.This gets trickier with async initialization methods. Think about a class, instances of which need to be initialized once only, before those can be used. In a non-async scenario one example would be to call the initialization method from the constructor, as follows:

public class SomeDirectory
{
  private Object state;

  public SomeDirectory()
  {
    this.Initialize();
  }

  // This method expects the state to be initialized before execution
  public void DoSomething()
  {
    // some logic
  }

  private void Initialize()
  {
    this.state = // state retrieval logic
  }
}

This gets complicated, when the initialization method becomes asynchronous. As constructors are non-async methods, the following transformation can lead to a situation, where instances of the SomeDirectory class aren't yet initialized after constructor, which can lead to some unexpected side-effects later, when the DoSomething method is called. The below sample code emphasizes the situation:


public class SomeDirectory
{
  private Object state;

  public SomeDirectory()
  {
    this.InitializeAsync();
  }

  // This method expects the state to be initialized before execution
  public async Task DoSomethingAsync()
  {
   // some logic
  }

  private async Task InitializeAsync()
  {
    this.state = // state retrieval logic
  }
}

A simple solution to this would be to force the constructor to wait for the initialization to complete:


  public SomeDirectory()
  {
    this.InitializeAsync().GetAwaiter().GetResult();
  }


This, however, is not a good technique, as it will introduce delay in the caller thread, which can harm in many situations (like in server code, where the actual DoSomethingAsync api is not being called immediately).

The third approach is calling initialization on every public API. Of course with a simple "run-only-once" optimization in it. Something like this:


public class SomeDirectory
{
  private readonly Object stateLock = new Object();
  private Object state;

  public SomeDirectory()
  {
  }

  // This method expects the state to be initialized before execution
  public async Task DoSomethingAsync()
  {
    await this.InitializeAsync();

   // some logic
  }
}

The problem with this approach is that it will slow down the very first call to DoSomethingAsync() method. Sometimes - it's something you don't want to have.
So here comes the final approach, which I'm using nowdays:


public class SomeDirectory
{
  private Object state;
  private readonly Task initializationTask;

  public SomeDirectory()
  {
    this.initializationTask = this.InitializeAsync();
  }

  // This method expects the state to be initialized before execution
  public async Task DoSomethingAsync()
  {
    await this.initializationTask;

   // some logic
  }

  private async Task InitializeAsync()
  {
    this.state = // state retrieval logic
  }
}

This approach will allow the execution of the initialization start as soon as the object is constructed. Yet, it won't loose the track of its execution.

Hope this will help some of you.

Friday, July 22, 2016

Unknown disposables: Disposing of non-disposable interface instances

In coding, it's a good practice to use factory methods (or some other creational design pattern) to abstract away creation of class instances. In most of the cases, the "creator" would return not the actual type being created, but the abstraction - the interface.
To emphasize the problem, let's consider the below example:

For simplicity, let's assume that we're dealing with a factory method, and the interface the factory method returns is called "IContract". Note, that IContract does not implement IDisposable. There are two different implementations of IContract - Impl and DisposableImpl. So here comes the interesting part, the DisposableImpl implementation does implement IDisposable.

So now, if one uses the factory method "Create()" to instantiate IContract, it may get a disposable instance back, and won't ever even know about it:

public class ContractFactory
{
    public IContract Create()
    {
        return new DisposableImpl();
    }
}

Obviously, the responsibility of disposing of the disposable instance is on the caller. A lot of people won't even notice the problem and just use the IContract and never worry about freeing up resources as early as possible. Yes, GC will eventually take care of the unnecessary resources, but that'll happen later than the actual variable becomes unnecessary - during finalization.

So one pattern a client can use is the following:

{
    IContract contract = null;
    try {
        contract = new ContractFactory().Create();
    // all the usage of the contract instance happens here
    }
    finally
    {
        IDisposable disposableContract = contract as IDisposable;
        if (disposableContract != null)
        {
            disposableContract.Dispose();
        }
    }
}


This will ensure safety in case of both disposable and non-disposable implementations.
Another way to go, would be to have a wrapper class, encapsulating the disposal logic and being a disposable itself, as follows:

public sealed class DisposableInterface<T> : IDisposable where T : class
{
    private readonly T interfaceInstance;

    public T Instance
    {
        get { return this.interfaceInstance; }
    }

    public DisposableInterface(T instance)
    {
        if (instance == null)
        {
            throw new ArgumentNullException("instance");
        }
       
        this.interfaceInstance = instance;
    }

    // A better implementation would be the usage of the Dispose pattern here.
    // Not doing that here to keep the sample simple.
    public void Dispose()
    {
        IDisposable disposableInstance = this.Instance as IDisposable;
        if (disposableInstance != null)
        {
            disposableInstance.Dispose();
        }
    }
}

Now, the caller could use the IContract as follows:
{
    using (DisposableInterface<IContract> contract = new DisposableInterface<IContract>(new ContractFactory().Create()))
    {
        IContract instance = contract.Instance;
        // all the interaction now happens with the "instance" reference
    }
}

As you can see, the second example is cleaner and nicer.
Now, as you're familiar with the problem, doesn't it raise a natural question: "should this become a pattern and be used all over the place with factory methods, as one can't know whether the actual implementation the factory methods returns will be disposable or not?"....
Think about this and leave any comments you may have.

Wednesday, June 17, 2015

"RunAs /NetOnly" functionality from C# code

Only recently I've learnt about the "/netonly" flag availability for "runas" command. I was really happy to find it, but the issue came later.
It turns out that the runas.exe command can't be automated, as it accepts passwords only through a prompt. So there is no way to pass in credentials without the prompt.

That made me seek for a custom solution for the problem. What it turned out is that the .Net Process API doesn't expose any functionality to control the process creation the way, which "/netonly" flag would results in.

Long story short, I came up with the following solution:
The CreateProcessWithLogonW Win32 API, which is being called internally by runas.exe, has a number of parameters indicating how exactly the process should be created. One of these parameters is "dwLogonFlags". The set of values it can take has one called "LOGON_NETCREDENTIALS_ONLY". From MSDN documentation for that value: "Log on, but use the specified credentials on the network only. The new process uses the same token as the caller, but the system creates a new logon session within LSA, and the process uses the specified credentials as the default credentials.". This is exactly what I need. After few hours of unsuccessful search for a C# code sample, which would create a process with this flag, I ended up creating my own.
The sample code is available for download at: http://1drv.ms/1LeqKnD

Hope you find this useful !