民间,
这段代码正是我想要的:
尽管它完全符合我的需要,但感觉这会导致代码审查失败。
是否有一些更好的模式来完成此任务,在 api 调用完成之前显示 div 并“思考”。
private async Task SendMessage()
{ var messageHolder = userMessage;
Console.WriteLine($"User Message is: {userMessage}");
if (!string.IsNullOrWhiteSpace(messageHolder))
{
messages.Add(new ChatMessageInPage { User = "User", Message = messageHolder });
var msg = new ChatMessageInPage { User = "Robot 🤖", Message = "Thinking..." };
messages.Add(msg);
userMessage = string.Empty;
// THS IS THE ODD CODE
Task.Run( async () =>
{
msg.Message = await apiRobot.GetBotResponse(messageHolder);
InvokeAsync(() =>
{
NeedScrollBottom = true;
StateHasChanged();
});
}
);
NeedScrollBottom = true;
StateHasChanged();
}
}
通常,这应该以更简单、更可靠的方式执行相同的操作:
if (!string.IsNullOrWhiteSpace(messageHolder))
{
messages.Add(new ChatMessageInPage { User = "User", Message = messageHolder });
var msg = new ChatMessageInPage { User = "Robot 🤖", Message = "Thinking..." };
messages.Add(msg);
userMessage = string.Empty;
// Simple code - display previous during await
NeedScrollBottom = true;
await Task.Delay(1); // optional, when the apiRobot isn't async enough
msg.Message = await apiRobot.GetBotResponse(messageHolder);
NeedScrollBottom = true;
}
当这不能按预期工作时,请发布确切的结果。