c# - 异步运行回调函数
问题描述
我试图了解如何在异步控制台应用程序中运行回调函数。我的基本控制台应用程序代码如下所示:
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# 经验是有限的。将不胜感激任何帮助!
解决方案
如果您直接使用异步方法,它不会阻塞调用者线程,您可以在任何地方调用它,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();
}
}
推荐阅读
- c++ - 如何获取数组第一个元素的镜像?
- stormcrawler - Stormcrawler:在 Elasticsearch 中存储抓取页面的外链
- sql - 如何根据值选择具有偏好的不同记录
- openedge - 我可以使用 Progress Developer Studio for OpenEdge 的哪个工具来测试 ABL 查询?
- kubernetes - 为什么运行的 pod json 中没有出现“版本”标签?
- powershell - 提取存档到传统文件夹结构
- glsl - 帮助理解简短的水彩着色器代码?
- javascript - 同步独立列滚动
- elasticsearch - 如何使用包含和正则表达式正确查询弹性搜索中的术语聚合值?
- c - 如何阻止我的玩家在我的游戏中离开网格?