On an ASP.NET C# page, I have an asynchronous initialAction
that needs to performed.
initialAction
involves the server sending a message over a WebSocket, and the server should wait for a while until the client responds. Once it responds, it should call onComplete
. I already have this part finished.
If the action does not complete its work in 5 seconds (for example), I want the script to move on. Currently, I make my script wait in a Task by repeatedly sleeping and checking a CancellationTokenSource
. If the CancellationTokenSource
is canceled by onComplete
or if 5 seconds has elapsed, the script will continue.
The below is the best method I've found. Is there a better way?
public static string wait(Action<Action<string>> initialAction)
{
string message = null;
using (CancellationTokenSource tokenSource = new CancellationTokenSource())
{
Action<string> onComplete = (msg) =>
{
message = msg;
tokenSource.Cancel();
};
Task sleepTask = new Task(() =>
{
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
if (tokenSource.IsCancellationRequested ||
stopwatch.ElapsedMilliseconds > 5000) { break; }
Thread.Sleep(10);
}
}, tokenSource.Token);
initialAction(onComplete);
sleepTask.Start();
sleepTask.Wait();
}
return message;
}