botframework-sdk icon indicating copy to clipboard operation
botframework-sdk copied to clipboard

How to a create a child thread or worker thread in Microsoft bot application

Open AnandChitale opened this issue 9 years ago • 2 comments

How to a create a child thread or worker thread in Microsoft bot application which can continuously listen to a third party Web APi and post to users on different connectors in per user per conversation context.

I created a bot and want that bot to listen to a third party Web API continuously. This work should be done in a separate thread. But if I create a thread in a Dialog class it does not post responses to user as dialog object gets suspended as it wait for user input.

RunChildTask method is called but does not post back to user

[Serializable] public class SampleDialog : IDialog { protected int count = 1; [NonSerialized] Thread ChildTask; public async Task StartAsync(IDialogContext context) {
ChildTask = new Thread(new ParameterizedThreadStart(RunChildTask)); ChildTask.Start(context); context.Wait(MessageReceivedAsync); }

private void RunChildTask(object context)
{
    IDialogContext contex = context as IDialogContext;
    while (true)
    {
        this.count++;
        contex.PostAsync($"{this.count++}: You said From child");
        Thread.Sleep(1000);
    }
}

public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var message = await argument;
    if (message.Text == "reset")
    {
        PromptDialog.Confirm(
            context,
            AfterResetAsync,
            "Are you sure you want to reset the count?",
            "Didn't get that!",
            promptStyle: PromptStyle.None);
    }
    else
    {
        await context.PostAsync($"{this.count++}: You said {message.Text}");
        context.Wait(MessageReceivedAsync);
    }
}

AnandChitale avatar Dec 02 '16 04:12 AnandChitale

Take a look at this sample: https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/core-CreateNewConversation

danmarshall avatar Dec 02 '16 19:12 danmarshall

Hi @AnandChitale let us know if this solves your issue. I'm going to close this for now, please feel free to open a new issue if you have any further specific questions.

danmarshall avatar Dec 06 '16 21:12 danmarshall