Search code examples
c#thread-sleep

Thread.Sleep(Int32) does not work C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Fuzzy.Test.DateTimeParserTests
{
    class TimeValidationTests
    {
        DateTime first = SayusiAndo.Tools.QA.BDD.Specflow.Fuzzy.Fuzzy.Parse("next week", DateTime.Now);
        Thread t = new Thread();
        t.Sleep(100);
    }
}

Gives me the error: Error 1 Invalid token '(' in class, struct, or interface member declaration and Error 2 'System.Threading.Thread.Sleep(System.TimeSpan)' is a 'method' but is used like a 'type'

I am using System.Threading. What am I doing wrong?


Solution

  • Two main points:

    Scoping

    From your problem perspective, you are calling it from an invalid scope. You cannot call methods from the class scope. In this case, you have to define a scope (like a Method for sample) to make this code works and call it. Read more about scoping in .Net.

    Sleep

    The System.Threading.Thread class has an static method called Sleep. This method has two overloads. The first one has an argument where an int is taken as milliseconds. The second one accept an TimeSpan. See the samples:

    // for 100 milliseconds
    System.Threading.Thread.Sleep(100);
    
    // for 5 seconds (using TimeSpan)
    System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
    
    // for 1 minute  (using TimeSpan)
    System.Threading.Thread.Sleep(TimeSpan.FromMinutes(1));
    

    From MSDN documentation about Thread.Sleep method:

    Blocks the current thread for the specified number of milliseconds.

    Conclusion

    Try a code like this:

    class TimeValidationTests
    {
      public void Interval()
      {
         // some code...
         Thread.Sleep(100);
      }
    }
    

    And instance it

    TimeValidationTests t = new TimeValidationTests();
    t.Interval();