LoginSignup
2
1

More than 3 years have passed since last update.

[C#]非同期非対応APIを簡単に非同期にするクラスTaskCompletionSource

Posted at

非同期に対応してないレガシーAPI

非同期に対応していない古いAPIは今どき困りものである。しかし.NETは簡単に非同期機能を追加できる便利な機構を持っている。拡張メソッドとTaskCompletionSourceクラスである。サンプル的な使い方はこんな感じ。

非同期に対応してないレガシーAPIを非同期に対応したモダンAPIに変えるサンプル

    class Program
    {
        static async Task Main(string[] args)
        {
            var oao = new OldApiObject();
            var a = await oao.DoAsync(true);
        }
    }

    static class OldApiEx
    {
        public static async Task<bool> DoAsync(this OldApiObject oao,bool flag)
        {
            var cs = new TaskCompletionSource<bool>();
            oao.Done += result => cs.SetResult(result);
            oao.Do(flag);
            //この時点でcs.Task.IsCompletedはTrue
            return await cs.Task;
        }
    }

    class OldApiObject
    {
        public event OldEventHandler Done;
        public delegate void OldEventHandler(bool flag);

        public void Do(bool flag)
        {
            Done(flag);
        }
    }

OldApiObjectが古いAPIである。DoneイベントとDoメソッドが用意されている。新たにOldApiExクラスを作成する。OldApiObjectに対して拡張メソッドを提供する。これにより使う側は古い新しいを意識せずに非同期機能を使うことができる。

今後、もうちょっとサンプルとか解説用意するかも

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1