Search code examples
c#taskdelaywait

Changing the delay timer? (c#)


Short Question. This is my Code.

var t = Task.Run(async delegate
{
    await Task.Delay(10);
    return 42;
});
t.Wait();

Thats what I will work with in General. But later in my Code I Need the delay to vary. I tried something like this already but I that does not seem right:

t.Wait(page*11);

(Whenever I click a button the variable "page" would Change. So Pretty much a new value everytime)


Solution

  • You could declare a variable and pass it's value to the delegate you pass in Task.Run as below:

    // define here the delayParam
    int delayParam = 10;
    
    var t = Task.Run(() => 
    {
        await Task.Delay(delayParam);
        return 42;
    });
    t.Wait();
    

    The return type of Task.Run is a Task<T> or just a Task if nothing it's returned. You can block on waiting the result of a Task, like you already do, by calling the Wait method. You can't pass arguments to the result...