栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将事件转换为任务的可重用模式

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将事件转换为任务的可重用模式

可以使用帮助器类和流利的语法:

public static class TaskExt{    public static EAPTask<TEventArgs, EventHandler<TEventArgs>> FromEvent<TEventArgs>()    {        var tcs = new TaskCompletionSource<TEventArgs>();        var handler = new EventHandler<TEventArgs>((s, e) => tcs.TrySetResult(e));        return new EAPTask<TEventArgs, EventHandler<TEventArgs>>(tcs, handler);    }}public sealed class EAPTask<TEventArgs, TEventHandler>    where TEventHandler : class{    private readonly TaskCompletionSource<TEventArgs> _completionSource;    private readonly TEventHandler _eventHandler;    public EAPTask(        TaskCompletionSource<TEventArgs> completionSource,        TEventHandler eventHandler)    {        _completionSource = completionSource;        _eventHandler = eventHandler;    }    public EAPTask<TEventArgs, TOtherEventHandler> WithHandlerConversion<TOtherEventHandler>(        Converter<TEventHandler, TOtherEventHandler> converter)        where TOtherEventHandler : class    {        return new EAPTask<TEventArgs, TOtherEventHandler>( _completionSource, converter(_eventHandler));    }    public async Task<TEventArgs> Start(        Action<TEventHandler> subscribe,        Action action,        Action<TEventHandler> unsubscribe,        CancellationToken cancellationToken)    {        subscribe(_eventHandler);        try        { using(cancellationToken.Register(() => _completionSource.SetCanceled())) {     action();     return await _completionSource.Task; }        }        finally        { unsubscribe(_eventHandler);        }    }}

现在,您有了一个

WithHandlerConversion
辅助方法,该方法可以从转换器参数中推断类型参数,这意味着您
WebBrowserdocumentCompletedEventHandler
只需要编写一次即可。用法:

await TaskExt    .FromEvent<WebBrowserdocumentCompletedEventArgs>()    .WithHandlerConversion(handler => new WebBrowserdocumentCompletedEventHandler(handler))    .Start(        handler => this.webBrowser.documentCompleted += handler,        () => this.webBrowser.Navigate(@"about:blank"),        handler => this.webBrowser.documentCompleted -= handler,        CancellationToken.None);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465253.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号