C
C#•9mo ago
doolhofx

Run code cyclical

Can anyone help me with running code cyclical? I have code that I want to execute every 10ms or 1 sec etc. And not just from an event, it needs to keep updating the code. Or just every cycle time I am mainly a PLC-programmer, don't know if C# also works with cyclic code execution the same as I am used to. C# 7.0, .NET Maui for android and windows
40 Replies
Pobiega
Pobiega•9mo ago
It doesn't work like a PLC at all. However, it is of course doable. The modern way to do this would probably be with a PeriodicTimer
doolhofx
doolhofxOP•9mo ago
I thought to already indeed Thanks I will search for it!
Pobiega
Pobiega•9mo ago
I don't know MAUI at all, so I don't know know how they prefer running background jobs, but the "normal" approach would be via a IHostedService (like BackgroundService, or make your own).
doolhofx
doolhofxOP•9mo ago
How do you mean that? Sorry I am a total ammateur in C#. Code that runs in the background?
doolhofx
doolhofxOP•9mo ago
https://www.youtube.com/watch?v=N7vhJ7O56iM&ab_channel=IAmTimCorey I am now following this video. But where do I place my code that is now inside the btn Clicked event? Just in the MainPage() ?
IAmTimCorey
YouTube
Periodic Timer in C# Including .NET 8 Updates
The PeriodicTimer allows us to run tasks on a timer in a way that is efficient and asynchronous. Instead of using the threading timer, a UI timer, or a DispatcherTimer and depending on callbacks, we can use this one timer to safely execute our code. Let's see how they work in this 10-minute training video. Full Training Courses: https://IAmTimC...
Pobiega
Pobiega•9mo ago
Why on earth are you doing MAUI if you are a beginner? O_O Its by far the most complicated project type with thousands of gotchas and problems.
doolhofx
doolhofxOP•9mo ago
Oh oops
Pobiega
Pobiega•9mo ago
However, thats sort of a side issue You are mentioning a click event, so how would this "cyclic" code execution interact with the button? does the button start it? if so, when does it stop?
doolhofx
doolhofxOP•9mo ago
I can programm, I know how the syntax and all works. And I can create a good console application but this with UI and so is totally new
Pobiega
Pobiega•9mo ago
what about threading?
doolhofx
doolhofxOP•9mo ago
Not, the button is removed and the code just needs to run
Pobiega
Pobiega•9mo ago
so it runs forever after the button is clicked? or is there no need for a button at all?
doolhofx
doolhofxOP•9mo ago
No button Just run the code over and over again
Pobiega
Pobiega•9mo ago
alright
doolhofx
doolhofxOP•9mo ago
I want a constant flow of data from my PLC --> application
Pobiega
Pobiega•9mo ago
right. Well, the problem you need to solve is how do we run this periodictimer without blocking the main UI thread we want the rest of the app to work as is while this works thats most often called "a background job"
doolhofx
doolhofxOP•9mo ago
Ooh yea that's with threading, right? multithreading
Pobiega
Pobiega•9mo ago
yeah, essentially but manually multithreading is hard and easy to get wrong luckily, .NET has a bunch of tools to help
doolhofx
doolhofxOP•9mo ago
nice!
Pobiega
Pobiega•9mo ago
again, I don't know MAUI. at all.
doolhofx
doolhofxOP•9mo ago
No problem, I think if I know the direction I have to goto I can figure it out
Pobiega
Pobiega•9mo ago
but in a console app, or a web api, or pretty much any other project type, you'd use the https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host?tabs=appbuilder and add your background job as a new hosted service but this kinda requires that you know and understand dependency injection and you'll likely want a messenger like MediatR or Immediate.Handlers to send messages from your job into your "main app"
doolhofx
doolhofxOP•9mo ago
I get it yes So it's not quite easy
Pobiega
Pobiega•9mo ago
not to do it well there are ways to do it "dirty" that are much simpler you certainly could just start a new thread and ask it to run your "cyclic" method that never returns
doolhofx
doolhofxOP•9mo ago
Isn't that enough? Or can those cause a lot of issues?
Pobiega
Pobiega•9mo ago
thats... fine. again dunno about MAUI, but in other GUI apps there is some complications about updating the GUI from the non-main thread
doolhofx
doolhofxOP•9mo ago
Can I send you a private message and give some more project background information? Maybe you know a total different way to achieve what I want? That is way more simpel haha
Pobiega
Pobiega•9mo ago
No thanks. Help here is done in public, not in private 🙂
doolhofx
doolhofxOP•9mo ago
Oke, no problem I understand it Uuh yea I got a PLC that also is a Modbus TCP slave (Server). I want to read data from that slave, so I have programmed a Modbus Master (client) in C# maui that works fine, but depends on the button click to read and write data from the PLC (slave). Now making it read/write every, for example, 1 second makes it easier to have a live view of what is happening
Pobiega
Pobiega•9mo ago
yeah I understand
doolhofx
doolhofxOP•9mo ago
Got it working now, don't know how clean it is but well.
private async void brnReadHolding_Clicked(object sender, EventArgs e)
{
using PeriodicTimer timer =
new(TimeSpan.FromMilliseconds(1000));
while (await timer.WaitForNextTickAsync())
{
//Code to execute
}
private async void brnReadHolding_Clicked(object sender, EventArgs e)
{
using PeriodicTimer timer =
new(TimeSpan.FromMilliseconds(1000));
while (await timer.WaitForNextTickAsync())
{
//Code to execute
}
Pobiega
Pobiega•9mo ago
thats indeed how you use a periodic timer but its still in a button click, and its an async void I guess being FNF isnt a huge problem for your app thou
doolhofx
doolhofxOP•9mo ago
I know, haha. Probably not super clean what is FNF?
Pobiega
Pobiega•9mo ago
fire 'n forget
doolhofx
doolhofxOP•9mo ago
Yea I guess so. Maybe I look into ending it with pressing the button again
Pobiega
Pobiega•9mo ago
that is actually fairly easy to do
doolhofx
doolhofxOP•9mo ago
You are probably laughing at my program but for a first Maui project I am actually glad how it is already as a start
No description
Pobiega
Pobiega•9mo ago
to easily cancel your timer gracefully, I recommend using a CancellationToken + CancellationTokenSource the basic idea is you just pass in a token object into your timer.WaitForNextTickAsync(cancellationToken) and then when that token is triggered by the CTSource, the timer function till return return false and thus stop
doolhofx
doolhofxOP•9mo ago
Oke, thanks I will try it
Pobiega
Pobiega•9mo ago
you'd need to move your timer stuff to a separate method and add some state to know if its already running or not
Want results from more Discord servers?
Add your server