首页 > 解决方案 > 异步运行回调函数

问题描述

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

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

标签: c#asynchronous

解决方案


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

推荐阅读