2 回答
TA贡献1820条经验 获得超10个赞
根据源代码 GetTickersWebSocket不是阻塞调用。
您发布的唯一阻塞调用是Console.ReadLine。 ExchangeBinanceAPI有它自己的基于回调的异步,所以,只需扔掉Console.ReadLine,或者在它之前放置更多代码:
static async Task MainAsync()
{
ExchangeBinanceAPI b = new ExchangeBinanceAPI();
using (var socket = b.GetTickersWebSocket((tickers) =>
{
Console.WriteLine("{0} tickers, first: {1}", tickers.Count, tickers.First());
}))
{
// code continues here
Console.WriteLine("Press ENTER to shutdown.");
Console.ReadLine();
}
}
作为旁注。
我对这个项目不熟悉,但源代码显示了里面的穷人的异步性WebSocketWrapper:
Task.Factory.StartNew(ListenWorkerThread)
// inside ListenWorkerThread
_ws.ConnectAsync(_uri, CancellationToken.None).GetAwaiter().GetResult();
result = _ws.ReceiveAsync(receiveBuffer, _cancellationToken).GetAwaiter().GetResult();
等等。
有尝试以同步方式调用异步代码。
取而代之的是,至少ListenWorkerThread必须转换为async方法,并且绝对不能通过Task.Factory.StartNew.
如果我必须使用这个项目,我会发布一个以真正异步方式重写代码的请求。
TA贡献1829条经验 获得超6个赞
如果您直接使用异步方法,则不会阻塞调用者线程,您可以在任何地方调用它,Consolo.ReadLine()然后Task根据需要使用返回来处理结果。
public static void Main(string[] args)
{
// Would not block the thread.
Task t = MainAsync();
// Only if you need. Would not block the thread too.
t.ContinueWith(()=> { code block that will run after MainAsync() });
// create a web socket connection to Binance. Note you can Dispose the socket anytime to shut it down.
// the web socket will handle disconnects and attempt to re-connect automatically.
ExchangeBinanceAPI b = new ExchangeBinanceAPI();
using (var socket = b.GetTickersWebSocket((tickers) =>
{
Console.WriteLine("{0} tickers, first: {1}", tickers.Count, tickers.First());
}))
{
Console.WriteLine("Press ENTER to shutdown.");
Console.ReadLine();
}
}
- 2 回答
- 0 关注
- 127 浏览
添加回答
举报