0

在 rx 你可以写:

var oe = Observable.FromEventPattern<SqlNotificationEventArgs>(sqlDep, "OnChange");

然后订阅 observable 将 sqlDep 对象上的 OnChange 事件转换为 observable。

同样,如何使用任务并行库从 C# 事件创建任务?

编辑:澄清 Drew 指出然后由 user375487 明确编写的解决方案适用于单个事件。任务一完成……嗯,它就完成了。

可观察事件可以随时再次触发。它可以看作是一个可观察的流。TPL 数据流中的一种 ISourceBlock。但是在文档http://msdn.microsoft.com/en-us/library/hh228603(v=vs.110).aspx中没有 ISourceBlock 的示例。

我最终找到了一个论坛帖子,解释了如何做到这一点:http ://social.msdn.microsoft.com/Forums/en/tpldataflow/thread/a10c4cb6-868e-41c5-b8cf-d122b514db0e

公共静态 ISourceBlock CreateSourceBlock(Action,Action,Action,ISourceBlock> executor){ var bb = new BufferBlock(); 执行者(t => bb.Post(t), () => bb.Complete(), e => bb.Fault(e), bb); 返回bb;}

//Remark the async delegate which defers the subscription to the hot source.
var sourceBlock = CreateSourceBlock<SomeArgs>(async (post, complete, fault, bb) =>
{
    var eventHandlerToSource = (s,args) => post(args);
    publisher.OnEvent += eventHandlerToSource;
    bb.Complete.ContinueWith(_ => publisher.OnEvent -= eventHandlerToSource);
});

我没有尝试过上面的代码。异步委托和 CreateSourceBlock 的定义可能不匹配。

4

2 回答 2

1

嵌入到 TPL 中的事件异步模式 (EAP) 没有直接等效项。您需要做的是TaskCompletionSource<T>在事件处理程序中使用您自己的信号。查看 MSDN上的此部分,了解使用 WebClient::DownloadStringAsync 演示该模式的示例。

于 2012-02-24T16:55:53.003 回答
1

您可以使用 TaskCompletionSource。

public static class TaskFromEvent
{
    public static Task<TArgs> Create<TArgs>(object obj, string eventName)
        where TArgs : EventArgs
    {
        var completionSource = new TaskCompletionSource<TArgs>();
        EventHandler<TArgs> handler = null;

        handler = new EventHandler<TArgs>((sender, args) =>
        {
            completionSource.SetResult(args);
            obj.GetType().GetEvent(eventName).RemoveEventHandler(obj, handler);
        });

        obj.GetType().GetEvent(eventName).AddEventHandler(obj, handler);
        return completionSource.Task;
    }
}

示例用法:

public class Publisher
{
    public event EventHandler<EventArgs> Event;

    public void FireEvent()
    {
        if (this.Event != null)
            Event(this, new EventArgs());
    }
}

class Program
{
    static void Main(string[] args)
    {
        Publisher publisher = new Publisher();
        var task = TaskFromEvent.Create<EventArgs>(publisher, "Event").ContinueWith(e => Console.WriteLine("The event has fired."));
        publisher.FireEvent();
        Console.ReadKey();
    }
}

编辑根据您的说明,这里是一个如何使用 TPL DataFlow 实现目标的示例。

public class EventSource
{
    public static ISourceBlock<TArgs> Create<TArgs>(object obj, string eventName)
        where TArgs : EventArgs
    {
        BufferBlock<TArgs> buffer = new BufferBlock<TArgs>();
        EventHandler<TArgs> handler = null;

        handler = new EventHandler<TArgs>((sender, args) =>
        {
            buffer.Post(args);
        });

        buffer.Completion.ContinueWith(c =>
            {
                Console.WriteLine("Unsubscribed from event");
                obj.GetType().GetEvent(eventName).RemoveEventHandler(obj, handler);
            });

        obj.GetType().GetEvent(eventName).AddEventHandler(obj, handler);
        return buffer;
    }
}

public class Publisher
{
    public event EventHandler<EventArgs> Event;

    public void FireEvent()
    {
        if (this.Event != null)
            Event(this, new EventArgs());
    }
}

class Program
{
    static void Main(string[] args)
    {
        var publisher = new Publisher();
        var source = EventSource.Create<EventArgs>(publisher, "Event");
        source.LinkTo(new ActionBlock<EventArgs>(e => Console.WriteLine("New event!")));
        Console.WriteLine("Type 'q' to exit");
        char key = (char)0;
        while (true)
        {
            key = Console.ReadKey().KeyChar;             
            Console.WriteLine();
            if (key == 'q') break;
            publisher.FireEvent();
        }

        source.Complete();
        Console.ReadKey();
    }
}
于 2012-02-24T17:03:31.670 回答