Is there a "Sleep" command? [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In a lot of languages, there's a
wait(milliseconds)
or
sleep(milliseconds)
command, that just makes your program not execute any more code until the sleep is up (this doesn't mean it stops the code that's running, it just pauses from running more. Is there a command like this in C#?
Thread.Sleep(time) doesn't work, it pauses all code that is currently executing as well (basically freezes your program)

Thread.Sleep(int milliseconds)
is what you're looking for

In C#, everything is running on one thread by default. If you want you can create another thread to run a specific piece of code. Then, you can sleep that thread so your app won't freeze.
Check this question out for more information: How do I run a simple bit of code in a new thread?

Yeap:
Thread.Sleep(milliseconds)
http://msdn.microsoft.com/es-es/library/system.threading.thread.sleep(v=vs.80).aspx

Yeah there is.
Thread.Sleep(milliseconds)
For example, if you use Thread.Sleep(5000) , it will make thread sleep for 5 seconds. Read more # MSDN

Thread.Sleep(milliseconds) should do it for you

You'll want to verify the syntax as I'm just wingin' it, but this will go into a non-blocking loop for the designated amount of time...
// Set the wait time
double waitTime = 5.0;
// Get the current time
DateTime start = DateTime.Now;
// Check the wait time
while(DateTime.Now.Subtract(start).TotalSeconds < waitTime)
{
// Keep the thread from blocking
Application.DoEvents();
}
That assumes you're using Windows Forms. If you're using WPF:
//Application.DoEvents();
this.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { }));
Again, you'll want to verify the syntax first...

Related

C# Thread.Run inside For loop what is the behavior [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I making an Experiment, I have a loop of 100000 increments and inside it there is a thread that does a specific task(write a log to DB), my question is when I run it its finish in one second maybe and it start to insert them lately, then how the OS handles them and it will process them all or will skip from them?
I try awaited method with them its good. but I want to know what will happen if this code was on a server and received 100000 requests.
The Code:
for (int i = 0; i < 100000; i++)
{
Task.Run(() => log.WriteToLog(i + "", new Models.CustomerModel.CustomerModel()));
}
I am not looking for alternative ways, I need to know the behaviour and how this code handles in OS (if there is a queue, some of them will run, etc..)
PS: I know its not a good approach
1 second is a bit quick. I suspect you are not logging 100000 entries properly and entries are being lost.
Assuming that code was the only code inside say a console app's main(), then because you don't await any of the tasks, it is entirely possible your process is exiting before the logging is complete.
Change:
Task.Run(() => log.WriteToLog(i + "",
new Models.CustomerModel.CustomerModel()));
...to:
await Task.Run(() => log.WriteToLog(i + "",
new Models.CustomerModel.CustomerModel()));
Also, as ckuri mentions in the comments, spawning a great deal of tasks in a tight loop probably isn't a good idea. Consider batching the logging or using IOCP.

Alternative to Thread.Sleep(); [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want a Method in C# which is going to make a break for 5 Seconds between 2 lines of codes.
Thread.sleep(5000);
isn't working because the rest of the code does also make a break. Have you got any Idea how to solve this?
falling.timespeed = 0.6f;
falling.fallingl = -50f;
// here I want a break for 5 Seconds
falling.timespeed = 1f;
falling.fallingl = -200f;
Are you familiar with the asynchronous features in modern c#?
In c# 5 and above:
async Task DoSomeWork()
{
// Do the first part of the work
await Task.Delay(5000); // Asynchronously wait for a 5 second timer to expire.
// Do the second part of the work
}
Note that, depending on the threading context that you call this method, part 2 may be executed on the same thread, or a different thread.

function repetition every 15 minutes c# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm doing some masks for SAP B1 using c#.
I'd need to know how to create a function that, automatically (for examples every 15 minutes), take some data and put its on a database.
The function is already done but how can I create the automatic execution in background?
Best regards and thanks in advance for the reply,
Lorenzo
Timer is what you need:
var timer = new System.Threading.Timer(
e => Method(),
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(15));
This will call Method() every 15 minutes.
Timer info : https://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
You could use Timer like #AmbroishPathak suggested. Also, as mentioned in the comments, you can use the Windows Task Scheduler to run your script or executable. The advantage of this is that the process won't be running in the background while it's not doing work.
You can see the details of how to schedule a task here.
The following answer describes this as well: windows scheduler to run a task every x-minutes?
To summarize the accepted answer there, you create the task to run once a day. After that, you can double-click on the task to bring up its Properties window and go to the "Triggers" tab. Under "Advanced Settings" you should be able to set it to run every x number of minutes.

All System.Threading.Timer instances in the process (including new ones) stops working after some while [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am encountering following issue in my .Net application:
It is a game server so there are around 150 threads to process all time-related logic, and some of them are Threading.Timer instances. The server was running fine at the beginning and to some point all timers stops working. I tried to start new timers via script executor. The new timers could be started but they are not firing events neither.
Anyone has idea about what could cause all the timers stop working in the process? I am not aware how could this happen theoretically.
System.Threading.Timer "executes a single callback method on a thread pool thread at regular intervals". Considering you are using 150 threads, its possible you are exhausing the thread pool.
Additionally, if you handler takes too long to process an event, Timer might fall behind and queue updates.
Re-think your design
Unless its a major component like scene loading; or audio playback; game makers generally avoid threading in games for reasons of reliability and simplicity.
Instead you may want to consider using:
deferred processing - delay processing until some time later
batch processing - rather than processing 10,000 items, process a batch of 100 items every 10ms
Gregory, J, "Game Engine Architecture"

Debug.WriteLine doesn't work on different threads [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
var timer = new Timer
{
Enabled = true,
Interval = 500
};
Debug.WriteLine("new timer created");
timer.Elapsed += (s, e) =>
{
Debug.WriteLine("hello from timer");
// this doesn't get shown
// in the output window
}
What do I need to do to be able to see my last Debug.WriteLine() in the output window above?
You are actually not using separate threads, the System.Timers timer runs on the UI Message pump if it is available. If you have blocked the UI thread the timer will never run.
Check either that the UI thread is not blocked, use System.Threading.Timer that does not use the UI thread, or set SynchronizingObject to null so it will use a threadpool thread instead of the UI thread.
EDIT: Or like Hans said in his comment, you are running in the console and Main() is exiting before the timer has a chance to fire.

Categories