What i want to achieve is to loop my code infinite times in my GUI/visual C# as i am reading information through a USB cable.
I have successful read the code but it only shows one reading every time i click the button. I understand that if i want my code to run infinitely, i will need to loop it.
I tried the code below but my program still hangs
while(true)
{
//loop
System.Threading.Thread.Sleep(10000);
}
I found this post and wanted to try the timer method however, i do not know where to put this code.
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
timer1.Interval=60000;//one minute
timer1.Tick += new System.EventHandler(timer1_Tick);
timer1.Start();
I am using Microsoft Visual studio 2010, anyone can guide me in using this code?
Please forget about creating such loops in your program, these will kill the UI thread that is actually running your UI, the result will be always bad!
You can run that timer, your code is missing the implementation of timer1_Tick, inside that function, run the code that you want. In your current configuration above, this timer will run every one minute and executes whatever is in timer1_Tick. This is a good Example.
Another option would be to create a thread that does the work for reading the USB and let the UI thread alone. I assume this is a harder option to implement for your so go with the timer option.
Related
I am learning to program in C# for .Net using VS2015 Community Ed.
Its my first question so if I am not in the correct format I apologize.
At present I am trying to click a button and have the program begin a countdown. This countdown item should be named (ie..Timer1) and its name appear in a ComboBox. That part is the easy part. The part where I am having an issue is figuring out how to have the timer continue if the program is terminated.
Is there a way to keep the countdown running after program termination until specifically terminated by the user? If so, What should I be searching for in order to learn this?
You could hide your form but the timer still continue, but there is no space for the timer to run if you close the application. It has to live in an application. I think what you're probably looking for is it living longer than your form, that is possible, just move the timer's scope up higher than the form, you'll have to play with the Program class, maybe make the form modeless instead of modal, or maybe not. You'll have to try a few ways. But the timer will have to run in your application, everything in your application dies when the application does.
The only way to have your timer continue to run after your process exits is to launch a separate process in which the timer will run. Of course, the original process will no longer have access to the timer, so you'll need to use some form of interprocess communication to allow the timer process to inform the original process of the timer state.
I've a set of queries which I want to execute only once in day, I know this is possible using TaskScheduler in C#. But I am not getting any example suitable for my requirements. Can anybody give a example code for this?
You can try FluentScheduler. The documentation has the sample codes all you need. Firstly I thought it is for web only, but now I think you can use it for using with Desktop Application too. But not sure and not tested.
https://fluentscheduler.codeplex.com/documentation
EDIT You can also use Task Scheduler -
First create a console application that can run and do all your tasks. You can even invoke other processes with it. Then build the executable and save it in a safe location.
Then go to Administrative Tools > Task Sheduler And create a new task by clicking Action > New Task. You will see a screen like this -
Select your executable and other permissions there.
Now to run it in schedule move to next tab 'Triggers' and click add at the bottom. You will see a screen like this -
Now add your desired schedules. Make sure you use logs, because you will not be able to see the outputs directly. Either you can use windows event viewer or write to custom text file for your convenience.
Task Scheduler is a part of windows itself. It does not have a
dependency on C# or C++ anything. Basically you tell windows that it
will run the specific program at a regular schedule. It is the job of the
executed program to initialize all environment and execute appropriate
code. So even if you use task scheduler you have to make sure that the
program you are using to run with it, has all other options and codes
right.
The Timer is probably the best solution for you.
var timer = new Timer {AutoReset = true, Interval = 30000}; 1s = 1000ms
timer.Elapsed += timer_Elapsed;
timer.Start();
.......
public void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
// do stuff here that will execute every 30 seconds
}
If you need a reliable scheduler, writing your own from scratch might take more effort than expected. What if the machine gets rebooted? What if it happens 10 seconds before execution time? Should the task be executed late or not at all? Where will the data be persisted? You have to think about all these things.
Alternatively, you could use Quartz.NET. It is a C# port of popular Java job scheduling framework. The codebase is well tested and robust. Have a look at it here:
http://www.quartz-scheduler.net/
I made a program based on Aforge (it's a video library). This library creates its own refresh events for the next video frame from camera. So far so good, earlier people have helped me with multi threading so these Aforge threads could report back to the main program thread, again so far so good, it works great.
The code can be seen here: how to do multithreading when using outside referenced code.
But now I regularly notice a new program error. The problem starts when I want to exit the program. At the moment the Aforge thread might still be active. And it wants to write back to main form that is closed.
Somehow I need to stop the other thread before I close the program. There is an option in Aforge to do something like camera stop, but it's not enough. But then still my code wants to write on the main form that's already closing.
Is there a way to stop all threads, or some safe way to close from the originating thread? I even placed the back reporting to the main program in a try catch construction but it didn't work well, the only way of stopping it in these situations is to press the stop execution button within Visual Studio itself.
If I understand your problem correctly, you may have an Invoke call about to happen on your form just as you've closed the form. I've had this happen as well.
What I've done is to set a "shutdown" variable when I start to close the form, and then use AppDomain.CurrentDomain.UnhandledException to watch for InvalidOperationException (or whatever you're getting), and ignore if shutdown is set.
I have created a windows application which is used to read every row from spreadsheet and pass each row of data to stored procedure. Assuming this work takes place for 2 hours(since there are large number of data's). And i have placed two buttons pause and cancel. On click of pasue, I need to pause the work of updating the work and need to resume when the button is pressed again. Please provide some inputs regarding this. I am using Visual studio 2003(with 1.1 framework) and SQL 2005. I am using c# for programming
Could you guys please explain how to put the main thread in background(while paused)... Please respond soon as it is urgent.
The operation of reading rows should be done on a separate thread. On that thread you should have something like this (note it is just the idea and not an exact code):
while(!mCancel)
{
if(mPaused==true)
{
Thread.Sleep(1000);
}
else
{
//do here the row reading
}
}
The mCancel and mPaused are global flags that you set to true or false from the UI buttons. When you press Pause button you set mPaused to true. At this point the loop will sleep for 1 sec and then reiterate and check for the flag again and if needed will sleep again.
Another way would be to use the ManualResetEvent class. See link for details. YHis class is used for signalign between threads, like the main thread and a worker thread for instance. Here is a sample.
Edit: The definitive guide to multi-threading by Joseph Albahari. Read this and all your threading problems will be solved.
In order to track the state of your pause button, you need to let the application process incoming messages from time to time. The implementation depends on the programming language being used and possibly the application framework.
I'm building a UI for a program, and I can't figure out why my progress bar won't become visible after the convert button is clicked.
private void convertButton_Click(object sender, EventArgs e)
{
toolStripProgressBar.Visible = true;
...
toolStripProgressBar.Visible = false;
}
I ran into a similar problem with tkinter in Python, and I had to call a function to update the idle tasks. Is there a way to do this with windows forms without using threads?
Edit: On a side note, this is a progress bar in a toolStrip that also contains a label that gets updated with status bar text. Is there any way to get the label on the left side and the progress bar on the other instead of right next to each other on the left?
Well, there is a way to do this without using threads (Application.DoEvents) but I strongly recommend against you using it. Re-entrancy is nasty, and you really don't want the UI thread tied up at all.
Use BackgroundWorker instead - it's easy, and it's pretty much designed for progress bars. It takes the hassle out of using a separate thread and reporting progress back to the UI thread. No need for Control.Invoke etc - it takes care of that for you.
There are lots of tutorials for BackgroundWorker - it shouldn't take you too long to get going with it.
Per the question you asked for the way to do this WITHOUT threads, that is to do it with Application.DoEvents();. (Just add that call right after setting the progress bar as visible.)
Now I do agree with Jon Skeet though that BackgroundWorker is a better way of doing this, but it does use a separate thread.
You need to execute your process in a thread separate from the UI thread, and then have it periodically report back to the UI thread with it's progress. If your convert operation is working inside the UI thread, it will simply go unresponsive until the operation is complete.
The progress bar can only become visible when it is allowed to paint which occurs during the processing of messages. Message processing cannot normally happen while you are in the middle of an event handler. If you want the progress bar to show up you will have to set the visiblitity to true, start a background thread to complete the work and return from the handler.
I'm guessing the problem is that the "..." in your code is a long-running process. UI updates are not instantaneous, but must run through the message queue in windows and then be painted to the screen. The queue is pumped and painting takes place in the same thread as your events.
As a result, any long-running tasks need to be moved to a different thread. More than that, your line line of code needs to called after that thread terminates. Otherwise you set the progress bar and then immediately turn it off again.
One way to do that is with a BackgroundWorker control.
Here go two links trying to explain you how things work:
(1) (2)
Now, I will try to explain it as shortly as I can. Most of what happens inside a windows forms application happens in a single thread, usually the same thread Main() runs in. If you open Program.cs, you will see that Main() has a line that looks like the following:
Application.Run(new Form1());
If you debug the application at any moment and examine the call stack, you will see it will trace back to that Run method. This means that a Windows Forms application is in fact a continuous run of the Run method. So, what is Run doing? Run is eating a message queue through which Windows sends messages to it. Run then dispatches those messages to the correct controls, which themselves do things like add text which corresponds to the key being pressed, redraw themselves, etc. Notice that all this happens during and endless loop running alongside a single thread, so weather you are typing or simply moving the window around, loads of those messages are being passed onto the application, which in turn is processing them and reacting accordingly, all in that single thread. Controls can also send messages to themselves through the queue and even you can place messages in the pump via Control.BeginInvoke. One of the things those controls do is to raise events according to what happens. So, if you click a button, the code you've written to handle that click will ultimately and indirectly be run by the Application.Run method.
Now, what is happening with your code is that even though you are changing the visible status of your progress bar to visible and then updating its Value, you are then changing its visibility to false, all in the same method. This means that only after you leave the method, will Application.Run() be able to continue iterating and consuming the message queue, effectively asking the progress bar to update its display. When that happens, you've already left the progress bar's visibility to false, the last thing you did before exiting the method. DoEvents() is a quick and dirty workaround to your problem as it reads the messages in the queue and processes them. I don't really feel comfortable using it as it can bring reentrancy problems.
Using threads is a good solution, but I would recommend using a ThreadPool thread instead of a custom thread in this kind of situation, as I tend to use custom threads only in cases where I have a limited number of long lived threads and I need to control their life cycles. The easiest and most practical way to use threads is to use the BackgroundWorker component, even though I would recommend going through the pains of understanding how to do Windows Forms multithreading with delegates if you want to really understand what is going on.
My solution is to call refresh on the status strip.
I believe this causes the UI thread to repaint the status strip.
toolStripStatusBar1.PerformStep();
statusStrip1.Refresh();
This is for .NET 4.0. Even though this question is old it was the first I found on googling this issue.