我的WebApi中的事件处理程序

本文关键字:事件处理 程序 WebApi 我的 | 更新日期: 2023-09-27 18:17:31

目前我必须连接到plc终端(基于tcp/套接字)。好的部分是制造商已经为我提供了一个抽象所有这些功能的dll。糟糕的是,所有程序都是用事件处理程序编写的。

的简化示例
public void GetOutputs(string id)
{    
    ConfigurationManager cm = new ConfigurationManager();
    cm.GetOutputResult += OnGetOutputResult;    
    cm.GetOutputAsync(id);
}
private void OnGetOutputResult(Output output)
{
    //do something here with the output when not null
}

我想创建一个WebApi项目,这样所有的"客户端"(UWP,Xamarin,ASP MVC)都可以通过http访问这个终端,这样就不会有便携式或。net Core库的麻烦,因为它们不能从制造商那里引用完整的。net Framework dll。

所以我的问题是:它甚至可能做这些事情在WebApi?有没有一种方法可以很好地将这些回调转换为可等待任务?

public class OutputsController : ApiController
{
    public IHttpActionResult Get(string id)
    {
        ConfigurationManager cm = new ConfigurationManager();
        //task/async/await magic here
        return Ok(output); // or NotFound();
    }

问候,错编

我的WebApi中的事件处理程序

您可以使用专为这种场景设计的TaskCompletionSource

private TaskCompletionSource<Output> tcs;
public Task<Output> GetOutputs(string id)
{    
    tcs = new TaskCompletionSource<Output>();
    ConfigurationManager cm = new ConfigurationManager();
    cm.GetOutputResult += OnGetOutputResult;    
    cm.GetOutputAsync(id);
    // this will be the task that will complete once tcs.SetResult or similar has been called
    return tcs.Task;
}
private void OnGetOutputResult(Output output)
{
    if (tcs == null) {
        throw new FatalException("TaskCompletionSource wasn't instantiated before it was called");
    }
    // tcs calls here will signal back to the task that something has happened.
    if (output == null) {
       // demoing some functionality
       // we can set exceptions
       tcs.SetException(new NullReferenceException());
       return;
    }
    // or if we're happy with the result we can send if back and finish the task
    tcs.SetResult(output);
}

在你的api中:

public class OutputsController : ApiController
{
    public async Task<IHttpActionResult> Get(string id)
    {
        ConfigurationManager cm = new ConfigurationManager();
        var output = await cm.GetOuputs(id);
        return Ok(output); // or NotFound();
    }