Search code examples
botframework

How to deal with timeouts in botframework SDK3 C#


I'm so sorry that I'm a newbie that I have so many questions.

My Bot state is save in DB. So it would never timeout. And I use teams. But I want to restart conversation if user don't reply for 10 minutes.

This is my solution. According this, I also made a static dictionary which could help me to handle every conversations' timer easily. And with the help of Sample Code, I did interrupt the stack. But once it's finished, it will be back to the original conversation. To solve this problem. I cleared the state according this


Solution

  • I'm sure there are a number of ways to solve this but here is one way you can try.

    In your Global.asax

    Define this cancellation token source for your thread

     CancellationTokenSource _getTokenAsyncCancellation = new CancellationTokenSource();
    

    In Application_Start() code setup a Task thread with a while loop. It will look something like this:

    Task.Factory.StartNew(async () =>
                {
                    while (!_getTokenAsyncCancellation.IsCancellationRequested)
                    {
                        try
                        {
                            //Check timespan between last message timestamp vs NOW
                            //if timespan > 9 minutes
                            //   send message 
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.Message);
                        }
                        await Task.Delay(TimeSpan.FromMinutes(1), _getTokenAsyncCancellation.Token).ConfigureAwait(false);
                    }
                }).ConfigureAwait(false);
    

    Also, add an Application_edn method to sht things down cleanly

    protected void Application_End()
            {
                _getTokenAsyncCancellation.Cancel();
            }
    

    Now, you're not quite done. You will also need somewhat to track the user's last message timestamp. Basically, each time the bot receives a new message from the user yo will set this timestamp and the code in your while loop will check against that.

    I hope this helps and gives you some ideas on what to try.