在.Net中,有很多关于如何在任务中包装EAP模式的页面,但不是为了转向另一个方向。没关系为什么,我知道想要这样做可能听起来很疯狂,但是如果这个库正在被那些不习惯async / await和Tasks的人消费。我已经提出了一个用事件模式包装Task的类,在InitEvents()方法中,我为 Canceled , ProgressChanged 和< em>完成事件到任务内部。
public class PackageOperation
{
public static PackageOperation GetPackageOperation<T>( T arg1,
Func<T, CancellationToken, Progress<ProcessedBoardArgs>, Task<IPackage>> func )
{
var progress = new Progress<ProcessedBoardArgs>();
var cancelTokenSource = new CancellationTokenSource();
Task<IPackage> packageTask = new Task<IPackage>(() =>
{
var inner = func(arg1, cancelTokenSource.Token, progress);
inner.Wait();
return inner.Result;
}, cancelTokenSource.Token);
var packageOperation = new PackageOperation();
packageOperation._packageTask = packageTask;
packageOperation._progress = progress;
packageOperation._cancelTokenSource = cancelTokenSource;
packageOperation.InitEvents();
return packageOperation;
}
private PackageOperation() { }
public PackageOperationProgressHandler ProgressChanged;
public PackageOperationCancelledHandler Cancelled;
public PackageOperationFinishedHandler Finished;
}
以下是它的使用方法:
public static PackageOperation GetPackage( PackageDescriptor pd )
{
return PackageOperation.GetPackageOperation<PackageDescriptor>(pd, GetPackageAsync);
}
private static async Task<IPackage> GetPackageAsync( PackageDescriptor pd,
CancellationToken token, IProgress<ProcessedBoardArgs> progress )
{
return await PackageParser.ParsePackage(pd.PackagePath, token, progress);
}
因此,除了从任务转移到EAP模式的明显问题之外,这还有效吗?它有什么明显的错误吗?