latte_makao
latte_makao

Reputation: 11

howto make a delay and how to start a function only in debug mode in c#?

I have two questions:

  1. How to make a delay in C#, I want to call a function after x Seconds when the program start, but the other things in the program should go on
  2. is it possible to call a function or a statement only when the program runs in debug mode?

Upvotes: 1

Views: 178

Answers (6)

Patko
Patko

Reputation: 4423

For the first option maybe the easiest way is the use of the ThreadPool.QueueUserWorkItem in combination with Thread.Sleep.

ThreadPool.QueueUserWorkItem(delegate {
  Thread.Sleep(numMilliseconds);
  // Your code here
});

Though if you block the thread for some time timers are probably a better solution.

Upvotes: 0

Shadow Wizzard
Shadow Wizzard

Reputation: 66388

I'm surprised nobody gave this yet..

if (System.Diagnostics.Debugger.IsAttached)
{
    //code to run when under debug
}

Upvotes: 1

Liviu Mandras
Liviu Mandras

Reputation: 6627

For #1 You need a Timer, that you start when the program starts and set it to tick at x seconds. You register for the Tick event of the timer that will be fired and there you call the method you want. Important: in the handler of the Tick event, before calling your method, you need to stop the timer. Otherwise it will keep calling your method at x seconds interval.

Here is a comparison between the different timers available in .NET.

For #2 You could use compilation directives:

#if DEBUG

CallMyMethod();

#endif

You can also use the Conditional Attribute.

    [Conditional("DEBUG")]
    public void CallMyMethod()
    {
        Console.WriteLine("This method will be called only when in DEBUG mode.");
        // notice the "DEBUG" string in the attribute parameter
    }

Upvotes: 3

vilqqu
vilqqu

Reputation: 1

For 2) note that if you want to run the program in debug mode without the function you can undefine the DEBUG by adding #undef DEBUG at the beginning of the file.

Upvotes: 0

rerun
rerun

Reputation: 25505

Question 1: can be solved by create a thread and having that thread sleep for x number of seconds then execute its code.

A small EX

static void Thread1()
{
    System.Threading.Thread.Sleep(5000);
    Console.WriteLine("hi");

 }

static void Main(string[] args)
{
    System.Threading.Thread T = new System.Threading.Thread(Thread1);
    T.Start();
    while (T.IsAlive)
    {
          System.Threading.Thread.Sleep(1000);
          Console.WriteLine("Waiting");

    }
    Console.WriteLine("Finished");

}

question 2: you can use #if

Upvotes: 0

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

1)Start a function in a separate thread and include Thread.Sleep() in that function.

2)Use #if DEBUG

#if DEBUG
MyMethod();
#endif

Upvotes: 1

Related Questions