可以将回调调用转换为IEnumerable

Gar*_*eth 8 c# callback enumerable

我正在编写第三方库的包装器,它有一种方法来扫描它管理的数据.该方法采用一种回调方法,它调用它找到的数据中的每个项目.

例如,该方法基本上是: void Scan(Action<object> callback);

我想包装它并公开一个类似的方法 IEnumerable<object> Scan();

这是否可以不使用单独的线程来进行实际扫描和缓冲?

por*_*ges 5

你可以用 Reactive 很简单地做到这一点:

class Program
{
    static void Main(string[] args)
    {
        foreach (var x in CallBackToEnumerable<int>(Scan))
            Console.WriteLine(x);
    }

    static IEnumerable<T> CallBackToEnumerable<T>(Action<Action<T>> functionReceivingCallback)
    {
        return Observable.Create<T>(o =>
        {
            // Schedule this onto another thread, otherwise it will block:
            Scheduler.Later.Schedule(() =>
            {
                functionReceivingCallback(o.OnNext);
                o.OnCompleted();
            });

            return () => { };
        }).ToEnumerable();
    }

    public static void Scan(Action<int> act)
    {
        for (int i = 0; i < 100; i++)
        {
            // Delay to prove this is working asynchronously.
            Thread.Sleep(100);
            act(i);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住,这不会处理取消之类的事情,因为回调方法实际上并不允许这样做。适当的解决方案需要外部库方面的工作。