Martin Voda
Martin Voda

Reputation: 19

Delay in program like as sleep()

I have a question about delay in Visual Studio 2010 C sharp. I need time delay in program for send position to servo. Now I am using System.Threading.Thread.Sleep(200)) but i need the delay which i can interupt.

When i use the sleep, that program during sleep not work. (on Click button,trackbar move ...), but I must control the program during the delay.

What is exist in VS like as function sleep?

Thank you very much for your reply.

Martin

Upvotes: 0

Views: 163

Answers (4)

Nerlog
Nerlog

Reputation: 261

Since you are using VS2010, you won't have access to C# 5 features (async / await keywords) and most probably are limited to .NET 4.0. Unfortunately that version does not have the Task.Delay method.

If that's the case the easiest option for you may be using either System.Threading.Timer or System.Timers.Timer depending on your needs. Both will execute a method on a thread pool thread after a delay. You can stop both of them before a tick and both of them support "infinite" periods.

Stopping the thread timer is not obvious, use Timer.Change method for this.

The links above have nice usage examples.

Upvotes: 0

Xander Luciano
Xander Luciano

Reputation: 3893

Use the Async Task.Delay() function with a cancellation token

Here's a quick example:

bool sendPos = true;

public async Task SomeFunction(CancellationToken token)
{
    while (sendPos)
    {
        SendServoPos();
        await Task.Delay(1000, token)
    }
}

public void MainFunction()
{
    var tokenSource = new CancellationTokenSource();

    // Fire and Forget - Note it will silently throw exceptions
    SomeFunction(tokenSource.Token)

    // Cancel Loop
    sendPos = false;
    tokenSource.Cancel();
}

Upvotes: 1

levent
levent

Reputation: 3644

you can work your process in async task without block your app.. and use Task.Delay() (its only block current task)

    public async Task SomeWork()
    {
        while (someCondition)
        {
            //do some work
            await Task.Delay(100);//milliseconds
        }
    }

Upvotes: 2

Matt Spinks
Matt Spinks

Reputation: 6700

You can use Task.Delay:

https://msdn.microsoft.com/en-us/library/hh194845(v=vs.110).aspx

public void mainFunction() {
  //do stuff here
  var delayTime = 1.5;
  CancellationTokenSource source = new CancellationTokenSource();
  var t = Task.Run(async delegate
  {
     await Task.Delay(TimeSpan.FromSeconds(delayTime), source.Token);
     delayableFunction();
  });

  //can cancel here if necessary
  source.Cancel();
  //just continue on with other stuff... 
}

public void delayableFunction() {
  //do delay-able stuff here
}

Upvotes: 1

Related Questions