2016-11-10 4 views
1

現在、私はplc-terminal(tcp/socketsベース)に接続する必要があります。良い部分は、製造元が私のためにこのすべての機能を抽象化したDLLを提供したことです。悪い部分は、すべてイベントハンドラでプログラミングされています。 私はすべての「顧客(UWP、Xamarin、ASP MVC)は、HTTPを通してこの端末にアクセスすることができますので、ポータブルまたはで大騒ぎがないので、WEBAPIプロジェクトを作成するこの私のWebApiのイベントハンドラー

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 
} 

の簡単な例。 NETコアライブラリを参照することはできません。

私の質問です:これらのことをWebApiでも行うことは可能ですか?これらのコールバックを待っているタスクにうまく変換する方法はありますか?

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

よろしく、 Miscode

答えて

1

あなたはあなたのAPIのシナリオ

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

のこの種のために設計されたTaskCompletionSourceを使用することができます。

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

私が説明することはできません私は今どのように愚かな気がする...私は完全な間違った方向に考えていた。私はほとんど私の質問で答えを書いた 'これらのコールバックをうまく待たせたいタスクに変換する'あなたの素早い応答をありがとう! :) – Miscode

+0

それはクールだ、非常に正当な質問! –

関連する問題