Question

On button click I have fired call to StartContinuousThread which keeps polling the server every one second.

public class ThreadsWindow
{
    CancellationTokenSource wtoken = new CancellationTokenSource();
    private void btnStartTest_Click(object sender, RoutedEventArgs e)
    {
        StartContinuousThread();
    } 

    void StartContinuousThread()
    {
        while(true)
        {
            var fact = Task.Factory.StartNew(() =>
            {
                CallServer();
                Task.Delay(1000, wtoken.Token);
            },
            wtoken.Token);
        }
     }
}

StartContinuousThread starts executing, but btnStartTest_Click event handler finishes its execution.

How StartContinuousThread method would be able to update UI in this case?

I wonder whether StartContinuousThread is also terminated with event handler, since there is no wait keyword for re-joining.

Please help!

Was it helpful?

Solution

If you goal is to poll the server every second you have a number of problem.

  1. There is no loop. You execute the method once and then stop.

  2. You create a task using Delay and then ignore it. You ought to be creating a continuation of that task to do the rest of the work to actually not do anything for a second.

Here is an implementation that addresses those issues:

private async Task StartContinuousThread(CancellationToken token)
{
    while (true)
    {
        token.ThrowIfCancellationRequested();
        await Task.Run(() => CallServer());
        await Task.Delay(1000, token);
    }
}

Another possibility, especially if you're using an older version of C#, would be to use a timer to run some code every second.

As for updating the UI; you can do so freely anywhere outside of the call to Task.Run in this example. In your example you'd need to use some mechanism to marshal back to the UI thread, such as capturing the UI's synchronization context and posting to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top