在异步

时间:2018-05-23 06:16:52

标签: c# asynchronous

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

    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#体验有限。将不胜感激任何帮助!

2 个答案:

答案 0 :(得分:1)

根据source code GetTickersWebSocket不是阻止电话。

您发布的唯一阻止通话是Console.ReadLineExchangeBinanceAPI有自己的基于回调的异步,因此,只需丢弃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();
    }
}

作为旁注。

我不熟悉这个project,但是源代码显示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调用。

如果我必须使用这个项目,我会以真正的异步方式发布重写代码的请求。

答案 1 :(得分:1)

如果直接使用,异步方法不会阻止调用者线程,您可以在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();
    }
}