蠢货之TaskCompletionSource 带事件的同步调用

看了这个文章 https://www.cnblogs.com/kewei/p/14339919.html

终于知道了事件的这种方式怎么来搞同步调用。看别人的文章。我copy一把。记录下。

因为拍黄片的不会调SignalR,我只好转成同步的。

[HttpGet]
public async Task<IActionResult> GetHubInfo()
{
try
{
TaskCompletionSource<string> _source = new TaskCompletionSource<string>();
var connection = new HubConnectionBuilder()
.WithUrl("http://127.0.0.1:9026/ChatHub")
.Build();
await connection.StartAsync();
using (connection.On<string>("ReceiveMessage", (s) =>
{

//这里我要copy一下别人的记录下,可能的情况。

//var tcs = new TaskCompletionSource<string>();

//var wc = new WebClient();

//wc.DownloadStringCompleted += (s, e) => {

//if (e.Error != null)

//tcs.TrySetException(e.Error);

//else if (e.Cancelled) tcs.TrySetCanceled();

//else tcs.TrySetResult(e.Result);

//};
_source.TrySetResult(s);
}))
{

TimeSpan timeout = new TimeSpan(0, 0, 5);
using var cts = new CancellationTokenSource();
cts.Token.Register(() => _source.TrySetException(new TimeoutException()), useSynchronizationContext: false);
cts.CancelAfter(timeout);
await connection.SendAsync("winFormsApp", "a", "b");

return Ok(await _source.Task);
}
}
catch (Exception ex)
{
return Ok(ex.ToString());
}
}

 

 

 

posted @ 2021-01-28 18:17  forhells  阅读(132)  评论(0编辑  收藏  举报