[Serializable]
public class RootDialog : IDialog<object>
{
public async Task StartAsync(IDialogContext context)
{
await context.PostAsync("RootDialog !");
context.Wait(MessageReceivedAsync);
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
await context.PostAsync($"You sent {activity.Text} which was {length} characters");
context.Wait(MessageReceivedAsync);
}
}
我理解语句context.Wait用于等待用户的下一条消息。 但是如果我发表我的RootDialog我的陈述 等待context.PostAsync(&#34; RootDialog!&#34;); 在我的陈述之后执行 await context.PostAsync($&#34;你发送{activity.Text},{length} characters&#34;); 也被解释了。
为什么?
为什么我没有在声明中暂停我的程序 context.Wait(MessageReceivedAsync); 在StartAsync函数中,就像我在MessageReceivedAsync函数中一样?
答案 0 :(得分:1)
这里的文档中有一些IDialogContext.Wait的描述:https://docs.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-dialogs#implementation-details
StartAsync方法使用continuation调用IDialogContext.Wait 委托指定新的时候应该调用的方法 收到消息(MessageReceivedAsync)。
使用BotBuilder SDK构建的僵尸程序是安静且无状态的,因为服务器本身不会跟踪或存储会话信息。 &#34; context.Wait(方法)&#34;并不意味着在这里冻结代码&#34;而是在下次消息来自用户时在对话框中恢复此方法。调用next的方法实际上是使用对话框序列化并存储在State Service
中(参见此处:Manage state data最后一个context.Wait(methodname)将在用户下次发送消息时调用同一对话的背景。
一个例子可能有用:
[Serializable]
public class RootDialog : IDialog<object>
{
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
{
var activity = await result as Activity;
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return our reply to the user
await context.PostAsync($"You sent {activity.Text} which was {length} characters");
context.Wait(MessageReceivedAsync2);
}
private async Task MessageReceivedAsync2(IDialogContext context, IAwaitable<object> result)
{
await context.PostAsync($"Second MessageReceived");
context.Wait(MessageReceivedAsync);
}
}
上面的代码将在MessageReceivedAsync和MessageReceivedAsync2之间来回切换用户发送的每条消息。