Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Consider a server with a performance-sensitive, highly-parallel, C# processing pipeline where we want to raise an event if something stops happening, e.g. the flow of media.
One theorized approach is to create a timer that is delayed continuously by the pipeline. By way of a simplistic example:
const int IDLE_MILLIS = 1000; // 1 second
Timer timer = new Timer(IDLE_MILLIS, () =>
{
Console.WriteLine("Pipeline is idle.");
});
void ProcessMediaFrame(MediaFrame frame)
{
timer.Change(IDLE_MILLIS, Timeout.Infinite);
// pipeline is not idle
}
How expensive is the Change method here? (https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer.change)
Does the Timer consume any resources while idle?
The performance note in the source code (thanks Codexer for linking the correct file) says your case is exactly what they've optimized for.
We assume that timers are created and destroyed frequently, but rarely actually fire.
...
timeouts for operations ... almost never fire, because the whole point is that the timer only fires if something has gone wrong.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 20 days ago.
Improve this question
Say I was making a game and let's pretend I was using a Console Application rather than using something like Unity etc etc.
And imagine I wanted to implement a game loop, the same concept would apply to a dedicated network server for the game.
This is usually how I would have done it, but is this a good option?
public void Start()
{
_isRunning = true;
var sw = new Stopwatch();
while (_isRunning)
{
sw.Start();
/* Update Game Logic */
sw.Stop();
var sleepDelta = Constants.Tickrate - (int)sw.ElapsedMilliseconds;
if (sleepDelta > 0)
Thread.Sleep(sleepDelta);
else
Console.WriteLine(
$"Server can't keep up!\nElapsed: {(int)sw.ElapsedMilliseconds}\nElapsed: {sleepDelta}");
sw.Reset();
}
}
What's the difference between doing that vs something like the Timer and using the OnElapsed event
This is usually how I would have done it, but is this a good option?
Something like this might very well be good enough. I would not expect a high accuracy from the Thread.Sleep, so it might depend on how tight timing requirements you have. For a console based game I would suspect this is not super critical. If you do need high accuracy timers you might want to read this question.
What's the difference between doing that vs something like the Timer and using the OnElapsed event
A timer would do more or less the same thing, but the Threading.Timer/Timers.Timer classes allow ticks to overlap each other if you are not careful, so you either need to be careful with how you are using it, or use something like PeriodicTimer.
You also need a bit careful since the console process will exit when the main method returns, at least for normal non-async main methods.
Timers are in some sense more useful for UI programs where you cannot have a 'main loop', and have specialized timers that run on the UI thread.
But if your method works, then leave it be. If you do not have any problems, chances are that changes will introduce new issues without actually improving anything.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is there any functionality in C# with Web, so that from UI, if a button is pressed, the execution should get stopped. (Here C# is already busy with some process execution)
For example:
while (something)
{
// do something
}
while (something)
{
// do something
}
If first while loop is under execution and from UI "stop execution" button is pressed then it should interrupt the whole execution and exit.
You mean like this?
private volatile bool _stop = false;
void OnCancelClick()
{
_stop = true;
}
void WorkerProcess() //In separate thread
{
while (!_stop)
{
// do something
}
}
There are a million ways to do it. This is probably the simplest to understand.
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 7 years ago.
Improve this question
I am retrieving data of about 100k rows from a database into a datagridview.This process takes up to 5-6 seconds.however during these seconds the user can't move the mouse or click any other button.how can I use aysnc/multithreading to achieve smooth user interface.
Look into the Task library and async, there's a whole section of C# for doing exactly this.
Basically you wind up with things like . . .
var records = await GetRecordsFromDatabase();
MyDataGridView.ItemSource = records;
private Task<IEnumerable<Record>> GetRecordsFromDatabase(){
return Task.Run(() => {
//do stuff the return IEnumerable<Records>
});
}
Note that while you can use threads, Tasks are a much better option in C# for async support.
Edit - most databases should support some async operation. In that case you'd likely have an async method to transform things from the database to the format you need. You'd also likely want to follow the convention of marking your own method as async. Something like . . . .
private async Task<IEnumerable<Record>> GetRecordsFromDatabaseAsync(){
var dbRecords = await Database.GetRecordsAsync();
//transform the database records and return them
}
And call it as above.
Let's assume you are doing all of this processor intensive work as a result of a button click. Hopefully you already have the work in a separate method and are calling that method from the click event. If you actually have all of your work inside the click event, move it out into its own method and call it from the click event handler.
Now that is still on a single thread. I'll just address using a separate thread here, though you should look into tasks on your own as well. To use a separate thread for the hard work, write 2 lines of code like this:
Thread t = new Thread(nameOfTimeConsumingMethod);
t.Start();
And that will do it. If you need to write output to, say, textBox1, you cannot do so directly from the new thread (no cross thread calls). But you can still write to that box easily enough indirectly like so.
BeginInvoke(new Action(()=>textBox1.text = "Hello world!"));
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a background worker that executes evry time when data recived on serial port, and inside is some code, i would like to play some music file, just the first time that background worker executes, can somebody please help me ?
code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
.....
s.play();
...
}
I would probably just use a boolean class level field and set it after first call to DoWork, and then check in each call to see if you need to initiate play.
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 9 years ago.
Improve this question
What is the Mutex and semaphore in C#? Where we need to implement?
How can we work with them in multithreading?
You should start at MSDN.
System.Threading.Mutex: A synchronization primitive that can also be used for interprocess synchronization.
System.Threading.Semaphore: Limits the number of threads that can access a resource or pool of resources concurrently.
Generally you only use a Mutex across processes, e.g. if you have a resource that multiple applications must share, or if you want to build a single-instanced app (i.e. only allow 1 copy to be running at one time).
A semaphore allows you to limit access to a specific number of simultaneous threads, so that you could have, for example, a maximum of two threads executing a specific code path at a time.
I'd start by reading this: http://www.albahari.com/threading/part2.aspx#_Synchronization_Essentials
and then bolster it with the MSDN links bobbymcr posted.
You might want to check out the lock statement. It can handle the vast majority of thread synchonization tasks in C#
class Test {
private static object Lock = new object();
public function Synchronized()
{
lock(Lock)
{
// Only one thread at a time is able to enter this section
}
}
}
The lock statement is implemented by calling Monitor.Enter and Monitor.Exit. It is equivalent to the following code:
Monitor.Enter(Lock);
try
{
// Only one thread at a time is able to enter this section
}
finally
{
Monitor.Exit(Lock);
}