logo
down
shadow

C# - Using Thread.Sleep precisely in a console application


C# - Using Thread.Sleep precisely in a console application

By : Matriux
Date : November 19 2020, 03:01 PM
I think the issue was by ths following , Well, for very precise timing, you should use multimedia timers. Next best choice would be Stopwatch
code :


Share : facebook icon twitter icon
Display remaining time for Thread.Sleep() in Console Application

Display remaining time for Thread.Sleep() in Console Application


By : 5anjay_5hr
Date : March 29 2020, 07:55 AM
this one helps. The current structure of your program does not support what you are trying to achieve.
When you call Thread.Sleep(int), it suspends the current thread for the specified time. By default, your program only runs as a single thread, so suspending that thread stops all your code from being run.
code :
class Program
{
    static void Main(string[] args)
    {
        Program program = new Program();
        program.startFeed();
    }

    // This is run on the main thread
    public void startFeed()
    {
        // Start a Timer on a new thread to do work with the ProcessData method
        // Pass null to its 'state' argument, wait 0 milliseconds before
        // running it, and run it once every 300000 milliseconds
        using (new Timer(ProcessData, null, 0, 300000))
        {
            // The Timer will only exist while we are inside the 'using' block;
            // stay here with a loop
            while (true)
            {
                // Write our status message
                Console.WriteLine("Waiting for data at {0}...", DateTime.Now);
                // We don't want this loop running ALL the time; add a small
                // delay so it only updates once every second
                Thread.Sleep(1000); 
            }
        }
    }

    // This is run on the background thread
    private void ProcessData(object state)
    {
        try
        {
            //My Application which i want to run continously 
            //when thread enters in run mode
        }
        catch (Exception xObj)
        {
            Console.WriteLine(DateTime.Now.ToString()
                + " >> Incoming Message Processing Error. >> "
                + xObj.Message);
        }
    }
}
Console Application Interval vs Thread.Sleep

Console Application Interval vs Thread.Sleep


By : Davis Nixon
Date : March 29 2020, 07:55 AM
I wish this helpful for you Unless your computer is so overloaded that the time to create a process every two minutes is a huge drain on resources, there's no benefit to having your program sitting in a loop waiting for two minutes, just so that it can poll the database.
The benefit of using scheduled tasks is that you can change the scheduled task frequency (make it once every five minutes, or once an hour, or whatever) without having to modify the program. Sure, you could use an application configuration file, but why? Why duplicate functionality that already exists in the operating system, and is more flexible.
Is it okay to use Thread.sleep as a timer in a console application?

Is it okay to use Thread.sleep as a timer in a console application?


By : nttdocomo
Date : March 29 2020, 07:55 AM
like below fixes the issue Java Thread.Sleep() does not guarantee exact time elapsed: it is only approximate "waiting" time
To better do a purpose like yours, you can use "Timer" class and the code will be better:
code :
  public class TimerDemo {

   private int ptr = -1;
   String[] myStringArray = {"H","e","l","l","o"};
   public static void main(String[] args) {

      final Timer timer = new Timer();

      // creating timer task, timer
      TimerTask task = new TimerTask() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
             System.out.println(myStringArray[++ptr]); 
             if (ptr == 4) { timer.cancel(); }    
        }

    };          

      // scheduling the task at interval
      timer.scheduleAtFixedRate(tasknew,0, 1000);      
   }
}
Thread.Sleep() doesn't work in application Console C#

Thread.Sleep() doesn't work in application Console C#


By : JasonStats
Date : March 29 2020, 07:55 AM
With these it helps The problem isn't the Thread.Sleep( ). You're using a StreamWriter and since your program is probably never closing, you need to flush the StreamWriter after you write.
Add
Thread Console Application without Blocking using AutoResetEvent, ManualResetEvent, or Thread.Sleep

Thread Console Application without Blocking using AutoResetEvent, ManualResetEvent, or Thread.Sleep


By : Godisalie
Date : March 29 2020, 07:55 AM
it helps some times
The problem is that I know that the AutoResetEvent, the ManualResetEvent, and the Thread.Sleep tools are all blocking routines - meaning my database calls will not be processed during this time.
code :
worker.DoWork += delegate(object s, DoWorkEventArgs e)
Related Posts Related Posts :
  • Access class item generated from xml using xsd.exe
  • Is there a shortcut to explicit named paramers when I call a method in C# for VisualStudio 2017?
  • Sorting datatables in a dataset with the datatable.name
  • Datagridview multilpe links
  • Correct pattern for exposing available actions
  • Local web application accepts numbers with comma and published does not
  • How to read an xml file using xmldataprovider in wpf C#
  • Windows service and Entity Framework
  • Visual Studio 2017 Docker support not available for ASP.Net Core Angular or React projects
  • Datacontext models with join
  • WPF: Increased window size decreases performance
  • Handling bad CSV records in CsvHelper
  • C# Displays file icons in asp.net on GridView nested
  • is there a way to get the file names which need to be updated if TFS status.Numoperations != 0?
  • Headless Firefox in Selenium C#
  • How do I start a .exe with a json string as parameter correctly?
  • StreamContent not loaded to the end
  • HAP parses formatting in HTML documents
  • repeat and count a loop in an unordered sequence in C#
  • Redundant Casting in Visual studio
  • Lost references in Visual Studio 2017 solution
  • Is there a way to add two numbers using a private constructor in C#
  • Is it possible to execute multiple SSH commands from a single login session with SSH.NET?
  • How can I get NHibernate to map to a Tuple or Class?
  • MVC 5 C# Window Authentication pop up when I navigate to a certain area
  • Mongo C# driver toJson() DateTime
  • Coprime integers
  • What is the purpose with files ending with *CS.cs in Xamarin Forms projects?
  • MVC5 / Entity | Update/Create Complex Model
  • How to return auto increment ID from SQL using Petapoco ORM in .NET MVC
  • Create new web app offline c# using Visual Studio
  • How many times is ordered the IEnumerable in this case?
  • C# error when update database 2008 to sql 2016
  • How to insert string in multiple continuous pattern in windows c#
  • How to send temp data from Partial View to its parent View
  • C# encapsulation when getting updates from asynchronous method
  • Asp net core Content Security Policy implementation
  • @Html.DropDownList() Placeholder as Disable and Selected
  • Set AM/PM in Material Time Picker WPF
  • Ninject passing reference in constructor
  • C# Entity Framework text SQL query wrapper
  • Core 2.0 MVC - AD Group Authorization for logging
  • Decentralized NLog Target per Http request
  • How to use x:Object and when?
  • Displays file icons in asp.net on GridView
  • How do I avoid two (or more) threads that work on a table at the same time to not work on same row?
  • Add xml attribute for property in DB First
  • How do i execute 2 sql queries by clicking a button [C#]
  • convert jsonstring to objects c#
  • How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
  • How to run a .NET Core console application on Linux
  • UI not updating for bound element
  • C# Odata v4 open type raw values
  • DocumentFormat.OpenXml Modify Creator Propery of Document
  • How to SetBasePath in ConfigurationBuilder in Core 2.0
  • ASP MVC5 public readonly variable changes value when it should not
  • How to conditionally select item from hashset with queryable linq?
  • Progress Bar C# not showing the real progress
  • Correct logic to reconnect in SignalR with HubConnection
  • ComboBox with two or more sections
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org