猿问

在异步中运行回调函数

我试图了解如何在异步控制台应用程序中运行回调函数。我的基本控制台应用程序代码如下所示:


    using Nito.AsyncEx;


    static void Main(string[] args)

    {

        AsyncContext.Run(() => MainAsync());

    }


    static async Task MainAsync()

    {



    }

我想在异步模式下运行的方法如下来自 websocket api:


using ExchangeSharp;


public static void Main(string[] args)

{

    // 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();

    }

}

上面的代码旨在锁定控制台应用程序并订阅接收数据的事件,并对接收到的数据执行某些操作。


我想要做的是在单独的线程或异步中运行上述内容,以便我可以在 MainAsync() 函数中继续我的代码。


我在这方面的 C# 经验是有限的。将不胜感激任何帮助!


至尊宝的传说
浏览 131回答 2
2回答

拉莫斯之舞

根据源代码 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.如果我必须使用这个项目,我会发布一个以真正异步方式重写代码的请求。

肥皂起泡泡

如果您直接使用异步方法,则不会阻塞调用者线程,您可以在任何地方调用它,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();    }}
随时随地看视频慕课网APP
我要回答