rx 的 Observable.FromEventPattern 的 TPL 等价物是什么?

发布于 2025-01-08 08:56:21 字数 1536 浏览 4 评论 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( 动作,动作,动作,ISourceBlock>执行人) { var bb = new BufferBlock(); executor(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 的定义之间可能不匹配。

In rx you can write :

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

and then subscribe to the observable to convert the OnChange event on the sqlDep object into an observable.

Similarily, how can you create a Task from a C# event using the Task Parallel Library ?

EDIT: clarification
The solution pointed by Drew and then written explicitely by user375487 works for a single event. As soon as the task finished ... well it is finished.

The observable event is able to trigger again at any time. It is can be seen as an observable stream. A kind of ISourceBlock in the TPL Dataflow. But in the doc http://msdn.microsoft.com/en-us/library/hh228603(v=vs.110).aspx there is no example of ISourceBlock.

I eventually found a forum post explaining how to do that: http://social.msdn.microsoft.com/Forums/en/tpldataflow/thread/a10c4cb6-868e-41c5-b8cf-d122b514db0e


public static ISourceBlock CreateSourceBlock(
Action,Action,Action,ISourceBlock> executor)
{
var bb = new BufferBlock();
executor(t => bb.Post(t), () => bb.Complete(), e => bb.Fault(e), bb);
return 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);
});

I've not tryed the above code. There may be a mismatch between the async delegate and the definition of CreateSourceBlock.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

黑色毁心梦 2025-01-15 08:56:21

TPL 中包含的事件异步模式 (EAP) 没有直接等效项。您需要做的是使用 TaskCompletionSource 您在事件处理程序中向自己发出信号。 查看 MSDN 上的此部分以获取示例它使用 WebClient::DownloadStringAsync 来演示该模式。

There is no direct equivalent for the Event Asynchronous Pattern (EAP) baked into the TPL. What you need to do is using a TaskCompletionSource<T> that you signal yourself in the event handler. Check out this section on MSDN for an example of what that would look like which uses WebClient::DownloadStringAsync to demonstrate the pattern.

二智少女 2025-01-15 08:56:21

您可以使用 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();
    }
}

You can use 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;
    }
}

Example usage:

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();
    }
}

EDIT Based on your clarification, here is an example of how to achieve your goal with 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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文