[英]Sync operation in async method - how to fix result not outputted correct and complete?
In this example.在这个例子中。 When I run this in the console, I dont get anything in MyList property so nothing is displayed on the screen.当我在控制台中运行它时,我在 MyList 属性中没有得到任何东西,所以屏幕上没有显示任何东西。 BUT, if I add a breakpoint, I do get the expected content in the list.但是,如果我添加一个断点,我会在列表中得到预期的内容。 Possibly because the method where MyList is populated is an async.. and the process of adding to list is a sync?可能是因为填充 MyList 的方法是异步的..而添加到列表的过程是同步的? How would you change this code so that MyList is always populated when Program runs?您将如何更改此代码,以便在程序运行时始终填充 MyList?
namespace ReceiverApp
{
static class Program
{
public static List<string> MyList { get; set; }
const string ServiceBusConnectionString = "Endpoint=sb://...";
const string QueueName = "...";
static IQueueClient queueClient;
static void Main(string[] args)
{
MyList = new List<string>();
MainAsync().GetAwaiter().GetResult();
foreach (var item in MyList)
{
Console.WriteLine(item);
}
}
static async Task MainAsync()
{
queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
RegisterOnMessageHandlerAndReceiveMessages();
await queueClient.CloseAsync();
}
static void RegisterOnMessageHandlerAndReceiveMessages()
{
var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
{
MaxConcurrentCalls = 1,
AutoComplete = false
};
queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
}
static async Task ProcessMessagesAsync(Message message, CancellationToken token)
{
// Process the message
MyList.Add(Encoding.UTF8.GetString(message.Body));
//await queueClient.CompleteAsync(message.SystemProperties.LockToken);
}
static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs args)
{
Console.WriteLine($"Message handler encountered an exception {args.Exception}.");
return Task.CompletedTask;
}
}
}
You're mixing a code that is intended for a continuous message recieving with a short lived and immediately ending console application.您正在混合用于连续接收消息的代码与短暂且立即结束的控制台应用程序。 If you set a delay after you invoke the registration of the handler, you'll see the messages populated.如果您在调用处理程序的注册后设置延迟,您将看到填充的消息。 But this is a wrong implementation.但这是一个错误的实现。 If you want a controlled way to receive messages, you shouldn't use message handler but a message receiver.如果您想要一种受控的方式来接收消息,则不应使用消息处理程序,而应使用消息接收器。
Also, closing a queue client will terminate the connection with the broker and prevent message recieving.此外,关闭队列客户端将终止与代理的连接并阻止消息接收。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.