gpt4 book ai didi

c# - 从遗留类(启动方法 + 事件)创建任务(或可观察对象)

转载 作者:行者123 更新时间:2023-12-04 02:26:50 26 4
gpt4 key购买 nike

我有一个遗留类,我想以更方便的方式使用它。

class Camera 
{
void RequestCapture();
public delegate void ReadResultEventHandler(ControllerProxy sender, ReadResult readResult);
public event ReadResultEventHandler OnReadResult;
}

类(class)管理一个拍照的相机。它的工作原理是:

  1. 调用 RequestCapture 方法
  2. 等待引发 OnReadResult(显然,您需要订阅此事件才能获取捕获的数据)

操作是异步的。 RequestCapture 是一种即发即弃操作(快速!)操作。几秒钟后,事件将引发。

我想像平常一样食用它 Task或作为 IObservable<ReadResult>但我很迷茫,因为它不适应异步模式,而且我从未使用过这样的类。

最佳答案

按照 this article 中的示例我的基本方法(未经测试!!)将是:

class AsyncCamera
{
private readonly Camera camera;

public AsyncCamera(Camera camera)
{
this.camera = camera ?? throw new ArgumentNullException(nameof(camera));
}

public Task<ReadResult> CaptureAsync()
{
TaskCompletionSource<ReadResult> tcs = new TaskCompletionSource<ReadResult>();
camera.OnReadResult += (sender, result) => {
tcs.TrySetResult(result);
};
camera.RequestCapture();
return tcs.Task;
}
}

可能的用法:

public async Task DoSomethingAsync()
{
var asyncCam = new AsyncCamera(new Camera());
var readResult = await asyncCam.CaptureAsync();
// use readResult
}

考虑到 Stephen 的评论进行编辑(感谢您!)

所以,这是我对取消订阅事件处理程序的幼稚看法。我没有时间进行任何测试,因此欢迎提出改进建议。

class AsyncCamera
{
private readonly Camera camera;

public AsyncCamera(Camera camera)
{
this.camera = camera ?? throw new ArgumentNullException(nameof(camera));
}

public Task<ReadResult> CaptureAsync()
{
ReadResultEventHandler handler = null;
TaskCompletionSource<ReadResult> tcs = new TaskCompletionSource<ReadResult>();

handler = (sender, result) => {
camera.OnReadResult -= handler;
tcs.TrySetResult(result);
};

camera.OnReadResult += handler;
camera.RequestCapture();
return tcs.Task;
}
}

以防评论被“清理”:斯蒂芬说

Unsubscription isn't handled in the MS examples, but it really should be. You'd have to declare a variable of type ReadResultDelegate (or whatever it's called), set it to null, and then set it to the lambda expression which can then unsubscribe that variable from the event. I don't have an example of this on my blog, but there's a general-purpose one here. Which, now that I look at it, does not seem to handle cancellation appropriately. – Stephen Cleary

我强调的。

似乎有效:https://dotnetfiddle.net/9XsaUB

关于c# - 从遗留类(启动方法 + 事件)创建任务(或可观察对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66886517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com