Function call in c# [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
call a function continuously in c# console application. without using infinite loop and recursion because if use those then cpu usage is more.please can any one help me to solve this problem.some one suggest me to use background thread, but it doesn't call the function continuously.
Thread th = new Thread(//fun);
th.IsBackground = true;
th.start();

Use a system timer with a short interval.
In the "tick" event of the timer:
Stop the timer
Call the function
Restart the timer
A system timer's event runs on a thread pool thread so your console app thread continues as normal. The function is run as frequently as the interval allows, for the duration of the application. No recursion. No infinite loops.

If you want to call it continuously, then a high CPU usage is necessary: because the CPU is always busy doing what you want.
If you want to have a lower cpu usage, then you cannot run your function continuously but only at a (possibly very small) interval.
You have to decide.

You can use the Thread code but a thread just effectively calls the function which means that your function needs to be recursive or that it needs to have an infinite loop.
public void StartThread()
{
Thread th = new Thread(function);
th.IsBackground = true;
th.start();
}
public void function()
{
//preferably have some way of killing this if needs be so don't necessarily use 'true'
while(true)
{
//do stuff
//sleep an appropriate amount of time to not overload the cpu
//This sleeps (basically pauses thread) for 10 milliseconds
Thread.Sleep(10);
}
}
Adding the Thread.Sleep will stop the overloading of the CPU which you were referring to. Just run sleep for an amount of time which is acceptable for your application. If it's updating a value on a GUI then the user won't really notice if the value gets updated every half second (Thread.Sleep(500)) or every milliseconds (Thread.Sleep(1))

I'm not sure I get your answer, but let me explain how a thread works.
Threads
Threading, in most programming languages, is the practice of effectively splitting up execution, into synchronous execution. What this means, is that two methods can run at the same time.
Common uses of a Thread
One example of the use of a thread, is to listen for incoming connections on a server. So you'd have a thread, something like:
while(true)
{
// Listen to incoming messages.
}
The infinite loop is because, at no point, do you want to stop listening for incoming messages. That is the role of the server; to manage connections. However, the thread is killed when the program execution finishes. The reason why this is considered common practice is, because of the fact that this is run on a separate thread, it doesn't impact performance as much as you might think. C# is very good at dealing with multiple threads; as are most languages.
Alternatives
Well, look at it like this. If you want to listen for 1000 cycles, then you will do something like:
while(count < 1000)
{
count++;
// Do some thread code.
}
It really depends on what you want the thread for, that defines the code that goes into the thread, and how long it will run for.

Related

Can Task.Delay cause thread switching? [duplicate]

This question already has answers here:
I thought await continued on the same thread as the caller, but it seems not to
(3 answers)
Closed 2 years ago.
I have a long running process that sends data to the other machine. But this data is received in chunks (like a set of 100 packets, then delay of minimum 10 seconds).
I started the sending function on a separate thread using
Task.Run(() => { SendPackets(); });
The packets to be sent are queued in a Queue<Packet> object by some other function.
In SendPackets() I am using a while loop to retrieve and send (asynchronously) all items available in the queue.
void SendPackets()
{
while(isRunning)
{
while(thePacketQueue.Count > 0)
{
Packet pkt = thePacketQueue.Dequeue();
BeginSend(pkt, callback); // Actual code to send data over asynchronously
}
Task.Delay(1000); // <---- My question lies here
}
}
All the locks are in place!
My question is, when I use Task.Delay, is it possible then the next cycle may be executed by a thread different from the current one?
Is there any other approach, where instead of specifying delay for 1 second, I can use something like ManualResetEvent, and what would be the respective code (I have no idea how to use the ManualResetEvent etc.
Also, I am new to async/await and TPL, so kindly bear with my ignorance.
TIA.
My question is, when I use Task.Delay, is it possible then the next cycle may be executed by a thread different from the current one?
Not with the code you've got, because that code is buggy. It won't actually delay between cycles at all. It creates a task that will complete in a second, but then ignores that task. Your code should be:
await Task.Delay(1000);
or potentially:
await Task.Delay(1000).ConfigureAwait(false);
With the second piece of code, that can absolutely run each cycle on a different thread. With the first piece of code, it will depend on the synchronization context. If you were running in a synchronization context with thread affinity (e.g. you're calling this from the UI thread of a WPF or WinForms app) then the async method will continue on the same thread after the delay completes. If you're running without a synchronization context, or in a synchronization context that doesn't just use one thread, then again it could run each cycle in a different thread.
As you're starting this code with Task.Run, you won't have a synchronization context - but it's worth being aware that the same piece of code could behave differently when run in a different way.
As a side note, it's not clear what's adding items to thePacketQueue, but unless that's a concurrent collection (e.g. ConcurrentQueue), you may well have a problem there too.

C# Restarting a thread with a different parameter

I want to start a background thread on some user event, in which I wait/sleep 10 seconds to do something if a variable changes between the time it was passed in and the time it is checked. However, during that 10 seconds, the same user event can repeat, and I want to interrupt & reset the thread to use the new variable and start back at 10 seconds.
For example,
private static int index = 0;
private static Thread myThread = null;
if(myThread != null && myThread.IsAlive) {
// need to 'restart' the thread with updated index
/* Suspend? Resume? */
} else {
// create a new thread and start countdown
myThread = new Thread(new ThreadStart( some_Thread(index) ));
myThread.Start();
}
I read that suspend() and resume() are antiquated, and I've read up some posts on Auto/ManualResetEvent, but they're not exactly what I'm looking for. It's probably something closer to Abort() then Start() a new one, but apparently that's unwise.
So any suggestions how to achieve this with one static thread handle? Again, the 10 seconds 'sleep' has to be interruptible and, thereafter, the thread be discardable or restartable. Thanks!
I want to start a background thread on some user event,
You are doing what we at SO call an "XY problem". You have a completely wrong idea about how to solve a problem and you are asking questions about how to make that wrong way work. Instead, concentrate on the user focussed problem you really have and ask about that.
in which I wait/sleep 10 seconds to do something if a variable changes between the time it was passed in and the time it is checked.
Don't do any of this stuff. If you're making a thread whose job it is to sleep, odds are good that you are doing something very, very wrong. Threads are expensive; only make a thread if you're going to be scheduling a CPU to service that thread.
When you are considering making a thread, ask yourself "would I hire a worker to do this task?" Ten seconds of computer time is ten billion nanoseconds; that's like hiring a worker and paying them to sleep for centuries. You'd never do that; you'd just put "do this later" on your to-do list, and come back to it later. If it gets cancelled, you'd take it off your to-do list.
What you want to do instead is make zero extra threads. Make a cancellable asynchronous workflow that awaits a Task.Delay before it does the work that must be done ten seconds later. If the user event happens during the delay then cancel the workflow and start a new workflow.
If the work that follows the delay is CPU intensive, then schedule a worker thread and await the result. If it is not -- if it is CPU work that comes back in say 30 ms or less -- then just run the work on the main thread. If it is IO gated, then use the asynchronous version of the IO API to stay on the main thread. You want to be making as few threads as you can get away with here.
Be careful. Even though everything is still on one thread, there are still race conditions that are possible in cancellable workflows like this. You still need to consider all possible interleavings of the non-dependent parts of your asynchronous workflows.

Delay and wake up a task from being executed? (Task.Delay?)

I have a situation where I have multiple threads being executed at once. In some cases these threads will be put in a while() loop for an unknown amount of time, and if a certain number of threads get caught in this loop then eventually the scheduler stops letting other threads be executed.
I was wondering if there is some way I could delay a thread from being executed (remove it from the scheduled list) and then let other threads in. Is it then possible to wake up that thread later by a threadID or something like that?
I am reading about Task.Delay and see it suspends execution from a timespan and that it is possible to time something out for an infinite amount of time, but is it possible to time it out indefinitely UNTIL a event occurs and then undelay it by some name or ID?
Edit: I thought this question was one that was harder to post code for, but more or less I have a situation where requests come in and are put into a loop like:
while(true){
//check for something that could make me want to delete this thread/request
//do some things
}
I had noticed that when I sent large number of requests that I never stopped ended up still in his loop (which I understand), but it seems the max amount of threads that could be doing this is 16/32 (depends on my computer that I run it on) and it is stopping other requests from being scheduled to run.
I wanted to know if inside the while() loop I could do something like this:
while(true){
//put this thread to sleep
//do some things that
//call some function to wake up the specific thread I need to do work on, before I put it back to sleep
}
The difference in this now is that instead of 16/32 threads running I can have 1 "king thread" that enters this while() loop that can 'do some things' and then wake up the thread that needs to be affected by the 'things'. Is there a way to sleep and wake up a specific thread so that other threads can be scheduled to run?
From the question I guess that you are running a busy waiting loop. That's pretty bad as you found out.
Make the loop wait for an event:
while (true) {
WaitForEvent();
DoWork();
}
This requires cooperation from the thread (or component) that makes the event happen. You could use a ManualResetEvent or a TaskCompletionSource to make this coordination happen.
I can't really be more specific because the question is not particularly concrete about the scenario. I hope this pushes you in the right direction.

Is it Really Busy Waiting If I Thread.Sleep()?

My question is a bit nit-picky on definitions:
Can the code below be described as "busy waiting"? Despite the fact that it uses Thread.Sleep() to allow for context switching?
while (true) {
if (work_is_ready){
doWork();
}
Thread.Sleep(A_FEW_MILLISECONDS);
}
PS - The current definition for busy waiting in Wikipedia suggests that it is a "less wasteful" form of busy waiting.
Any polling loop, regardless of the time between polling operations, is a busy wait. Granted, sleeping a few milliseconds is a lot less "busy" than no sleep at all, but it still involves processing: thread context switches and some minimal condition checking.
A non-busy wait is a blocking call. The non-busy version of your example would involve waiting on a synchronization primitive such as an event or a condition variable. For example, this pseudocode:
// initialize an event to be set when work is ready
Event word_is_ready;
work_is_ready.Reset();
// in code that processes work items
while (true)
{
work_is_ready.Wait(); // non-busy wait for work item
do_work();
}
The difference here is that there is no periodic polling. The Wait call blocks and the thread is never scheduled until the event is set.
That's not busy waiting. Busy waiting, or spinning, involves the opposite: avoiding context switching.
If you want to allow other threads to run, if and only if other threads are ready to run, to avoid deadlock scenarios in single threaded CPUs (e.g., the current thread needs work_is_ready to be set to true, but if this thread doesn't give up the processor and lets others run, it will never be set to true), you can use Thread.Sleep(0).
A much better option would be to use SpinWait.SpinUntil
SpinWait.SpinUntil(() => work_is_ready);
doWork();
SpinWait emits a special rep; nop (repeat no-op) or pause instruction that lets the processor know you're busy waiting, and is optimized for HyperThreading CPUs.
Also, in single core CPUs, this will yield the processor immediately (because busy waiting is completely useless if there's only one core).
But spinning is only useful if you're absolutely sure you won't be waiting on a condition for longer than it would take the processor to switch the context out and back in again. I.e., no more than a few microseconds.
If you want to poll for a condition every few milliseconds, then you should use a blocking synchronization primitive, as the wiki page suggests. For your scenario, I'd recommend an AutoResetEvent, which blocks the thread upon calling WaitOne until the event has been signaled (i.e, the condition has become true).
Read also: Overview of Synchronization Primitives
It depends on the operating system and the exact number of milliseconds you are sleeping. If the sleep is sufficiently long that the operating system can switch to another task, populate its caches, and usefully run that task until your task is ready-to-run again, then it's not busy waiting. If not, then it is.
To criticize this code, I would say something like this: "This code may busy wait if the sleep is too small to allow the core to do useful work between checks. It should be changed so that the code that makes this code need to do work triggers that response."
This poor design creates a needless design problem -- how long should the sleep be? If it's too short, you busy wait. If it's too long, the work sits undone. Even if it's long enough that you don't busy wait, you force needless context switches.
When your code is sleeping for a moment, technically it will be in sleep state freeing up a CPU. While in busy waiting your code is holding the CPU until condition is met.
Can the code below be described as "busy waiting"? Despite the fact that it uses Thread.Sleep() to allow for context switching?
It is not busy waiting, rather polling which is more performant that busy waiting. There is a difference between both
Simply put, Busy-waiting is blocking where as Polling is non-blocking.
Busy waiting is something like this:
for(;;) {
if (condition) {
break;
}
}
The condition could be "checking the current time" (for example performance counter polling). With this you can get a very accurate pause in your thread. This is useful for example for low level I/O (toggling GPIOs etc.). Because of this your thread is running all the time, and if you are on cooperative multi threading, the you are fully in control, how long the thread will stay in that wait for you. Usually this kind of threads have a high priority set and are uninterruptible.
Now a non-busy waiting means, the thread is non-busy. It allows another threads to execute, so there is a context switch. To allow a context switch, in most languages and OS you can simply use a sleep(). There are another similar functions, like yield(), wait(), select(), etc. It depends on OS and language, if they are non-busy or busy implemented. But in my experience in all cases a sleep > 0 was always non-busy.
Advantage of non-busy waiting is allowing another threads to run, which includes idle threads. With this your CPU can go into power saving mode, clock down, etc. It can also run another tasks. After the specified time the scheduler tries to go back to your thread. But is is just a try. It is not exact and it may be a little bit longer, than your sleep defines.
I think. This is clear now.
And now the big question: Is this busy, or non-busy waiting:
for(;;) {
if (condition) {
break;
}
sleep(1);
}
The answer is: is is a non-busy waiting. sleep(1) allows the thread to perform a context-switch.
Now the next question: Is the second for() busy, or non-busy waiting:
function wait() {
for(;;) {
if (condition) {
break;
}
}
}
for(;;) {
wait();
if (condition) {
break;
}
sleep(1);
}
It is hard to say. It depends on the real execution time of the wait() function. If it does nothing, then the CPU is almost the entire time in sleep(1). And this would be a non-blocking for-loop. But if wait() is a heavy calculation function without allowing a thread context switch, then this whole for-loop may become a blocking function, even if there is a sleep(1). Think of the worst-case: the wait() function is never returning back to caller, because the condition isn't hit for a long time.
This here is hard to answer, because we don't know the conditions. You can imagine the problem, where you cannot answer the question, because you don't know the conditions, in the following way:
if (unkonwnCondition) {
for(;;) {
if (condition) {
break;
}
}
} else {
for(;;) {
if (condition) {
break;
}
sleep(1);
}
}
As you see, its the same: because you don't know the conditions, you cannot say if the wait is busy or non-busy.

can we use "goto" keyword to end a thread? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In many programming languages, many questions have been raised to stop execution of a thread.In c/c++ goto is still used, where as in Java , goto is not used,but still it's reserved; stop(), stop(Throwable) and suspend(), destroy() and resume(), which were intended to provide the basic functionality for starting and stopping a thread has been depreciated.
Can we use goto to simply to move out of a thread?
Somethig like this :
//Thread block
{...
if(some condition)
goto out;
.....
...
}//thread block over
out:
// I am out!!
}
I know using goto is a very very bad practice, but can still it be used like this?
UPDATE:
Or:
//Thread block
{...
if(some condition)
goto out;
.....
...
out:
// I am out!!
}//thread block over
From the comments,is this the solution?
UPDATE2:
Well,I am getting mix kind of answers.Some yes,some no.I don't use c/c++ much ,otherwise could have implemented and see myself.
This doesn't work.
You can't goto to another method.
A thread is not bound to a method and one method can be executed by multiple threads.
If the goto location would be in the same method, the execution would simply continue at the new location in the thread that executed the goto statement.
What you can do, is go to the end of the thread method - if the current code is in that method. This won't end the thread, but the goto will move the program flow just before the end of the thread method which will lead to the thread method being finished executing and thus ending the thread.
This is the same effect as simply returning from the thread method.
Absolutely, you can: you can use goto to transfer control unconditionally to the end of your method from almost anywhere, with very few restrictions. If this is the method that implements your thread, it will exit, ending the thread.
Whether you should is a different question: with very few exceptions, goto makes your program less readable; without exceptions, you can achieve the same result without a goto, and improve readability at the same time. For example, you could use return to end the method implementing the logic of your thread.
You can't "move out" of a thread using goto. A thread's execution is not limited to a given scope and just moving to another location in your code will not terminate it.
You can not goto to a label out of the your thread function
You can set the out: at the end of the thread functio. And in this way if you want to stop your thread you can goto the out: (from any place in your thread function) and the thread function will be stopped
If you want to execute some part of your code at the end of your thread you can use pthread_cond_signal(&cond);
the following link contains an example of how to use it: multithread launching order
No you can't.
But perhaps you don't need to... You can try to use ThreadAbortException (by calling Thread.Abort()) and catch it (yes, within the thread), executing the 'out' functionality, and do a Thread.ResetAbort. Just be careful and be sure to read up on the risks involved on MSDN when calling abort from another thread (which you don't seem to be doing).
See also: http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx
First of all, putting cleanup code at end of function, and jumping to it with goto is quite valid pattern in C. Use it when ever it makes the code cleaner and easier to understand. Of course it can be abused, and it doesn't work that well when you have multiple levels of functions, so it might encourage making too long functions just to be able to goto to cleanup code. But as long as it's used carefully, goto is quite valid in C. Also, since the question is a bit vague, better say this explicitly: you can not goto between functions. And in languages supporting exceptions, you should use those instead of goto (of course you have to use them right too, not abuse them).
But often, especially with threads, it is better to register cleanup handlers for the thread, so you can then just return or call the thread frameworks "exit this thread" function, instead of using goto to cleanup code.
Finally, with the code above, with no code after out: label, you could just return instead of using goto... This assumes you are using a threading library, which takes a function to run in other thread, and will end the thread when that function returns.

Categories

Resources