Websocketharpライブラリのリクエスト/レスポンスパラダイムを実装しようとしていますが、これはHttpClientのリクエスト/レスポンス非同期動作とまったく同じです。私は以下のコードで与えられたasyncコールバックを使用してそれを達成しようとしています。 SendAsyncメソッドのOnMessageコールバックイベントを取得して、サーバーが応答を送信するまで待機させようとしました。私はSendAsyncメソッドの範囲内で応答を取得することができますが、SendAsyncスコープから出てすぐに応答の値をクリアします。Websocket.SarpAsync()とOnMessageコールバック関数を使用したWebsocketsharpライブラリのリクエスト/応答パラダイム
string clientResponse = null;
var response = Task.Run(() => objWSClient.SendAsync(stream, Convert.ToInt32(stream.Length), (async (completed) =>
{
if (completed)
{
clientResponse = await WSMessageSendSuccess(reqObject, callback);
// Websocket response is flushed to the console window, but when it leaves the scope, it doesn't hold the response out of the SendAsync() scope.
Console.WriteLine(clientResponse);
}
else
{
WSMessageSendFail(reqObject);
clientResponse = "Failure to send Message";
}
})));
while (response.Status != TaskStatus.RanToCompletion)
{
Task.Delay(10000).Wait();
}
response.Wait();
// As soon as we leave scope of WebSocket.SendAsync() method, it clears the client response variable value.
// variable name : clientResponse;, it also works same with static property/variable.
return clientResponse;
あなたは、Microsoftの記事、https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/interop-with-other-asynchronousに従うことによってAPIをカプセル化することができます-patterns-and-types#task-and-the-event-based-asynchronous-pattern -eap –