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 7 years ago.
Improve this question
I'm newbie at C#, and I'm struggling with Threading(maybe).
When I start debugging, and execute one by one, ...and loading form is completed, procedure is placed at strange position like this :
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length > 0)
Application.Run(new frmMain(args[1]));
else
Application.Run(new frmMain());
} // Stops here
I suspected it is normal, so I created new project and executed. and result was different with before like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); // Stops here
}
Now I'm very confused, So I need a help. someone tell me it is threading, but I didn't used any threading in my code.
P.S. I used NAudio Library to play music so I declared on frmMain class like this:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using NAudio;
using NAudio.Wave;
using TagLib;
(...)
AudioFileReader _audioFileReader;
IWavePlayer _waveOutDevice = new WaveOut();
(...)
P.S. 2 ..And this is constructor of frmMain.
InitializeComponent();
this.listMusic.DragOver += new DragEventHandler(this.FileDragOver);
this.listMusic.DragDrop += new DragEventHandler(this.FileDragDrop);
this.listMusic.DoubleClick += new EventHandler(this.listDoubleClick);
_waveOutDevice.PlaybackStopped += new EventHandler<StoppedEventArgs>(this.PlaybackStopped);
It could be that another part of the code is using multiple threads. I've had situations where there were multiple threads and as I single-stepped through code, the current location bounces around. It's not really a problem as long as you understand what it's doing, but if you halt execution in the debugger, it can stop somewhere you don't expect.
If you want to stop execution in your code, place breakpoints (F9) on lines of your code, then, when you've started an operation that enters your code, step through as desired.
If you're curious about what other threads are running, there is the Threads window; while debugging, go to the Debug window, select Windows, then Threads. If you're not creating threads of your own, it may or may not be useful, but sometimes it's handy to see what might be loaded when you pause execution in the debugger.
Related
This question already has answers here:
How can I execute code after my form starts?
(5 answers)
Closed 5 years ago.
I am fairly new to C# but I feel like this should output "hi":
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace PathMet_Controller
{
class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Debug.WriteLine("hi");
}
}
}
My output window gives me this:
In playing around, it did output "hi" once, but it would only output after I stop running the file.
Because Application.Run will start special loop which will end when you exit your win forms application.
If you want to print something at start, use events provided by Form class.
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 7 years ago.
Improve this question
Hello I wanted to know what is the best way to keep a console open forever? I want the fastest way, the most stable way, basically the best way to keep it open forever untill I close it.
I have recently been using the code below, but someone has said while loops are not good? or something like that, or storing stuff inside them isn't good? I basically just wanted your guys advice on what is the overall best way to do this? or a few of the best ways...
while (true) //in Program.cs in void Main
Console.ReadKey();
Do a simple Console Application and it will be open until the end of the execution. If you close the console you close the app. If you dont need the console it will remain open until the app is done running (so no loop or anything) and when you will be ready to use it, it will still be there waiting for you.
EDIT:
You might want to consider doing a Service application then. You wont have any console running and the application will be standing there behind and no one will see a black box and risk of closing it by mistake. You can then stop it with the Service Panel. The core of your service will be a simple thread waiting on a signal (a player connect). so your app run 24/7 without any problem and can be close easily.
I see no problem with a loop. I would have a command that can be input to close the window from a text input though. Something like:
string s = "";
while (s != "kill")
s = Console.ReadLine();
Some times while(true) loops can be dangerous because they will always run but I feel a while loop is fine. I have used this code for servers and the like. It has never been a problem for me.
So in your comment you say:
I want to keep it open 24/7 untill I hit "X"
In this case, do this:
Console.WriteLine("Press X to stop");
do
{
while (!Console.KeyAvailable)
{
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.X);
Console.WriteLine("Stopped");
As other people are pointing out, while(true) would be a performance hog.
Maybe (there is not enough info to know that) what you want to do as well is to start a thread before the loop, and kill it after the loop. This way your functions run parallel to the loop but you are in control of killing it whenever you want (pressing X). To do this in a clean way, follow the example at the bottom of the page.
...or by brute force:
Console.WriteLine("Running the process");
System.Threading.Thread workerThread = new System.Threading.Thread(MyFunction);
workerThread.Start();
Console.WriteLine("Press X to stop");
do
{
while (!Console.KeyAvailable)
{
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.X);
workerThread.Abort();
Console.WriteLine("Stopped");
I have a C# application that consists of multiple forms, and there is no particular one which will always be closed last.
Where should I put a piece of code (i.e. dumping some information to a file) to ensure that no matter how the program exits, this happens just before the program closes?
Well one option would be to call a method to do what ever you want right before the main method exits.
ETA:
by default the main method is in the program.cs file.
here is an example of what I mean
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
//** this code will not be reached until form1 closes.
bool blah = true;
doWhatEver(blah);
}
i am not really sure how to ask this question properly. so apologies in advance.
but it's basically around how to make an existing app, with a UI, run as a scheduled task with no UI.
background..
I have a winforms app written in vs2012 with 2 forms.
the first form is the login, straight forward, but currently expects user interaction of their username and password.
the second is the main form. which does the main work when you hit the "start" button.
what I am trying to achieve it is for me to send it some command line parameters that would run it without any ui as a scheduled task.
so, I'm guessing, I need get rid of needing the user to input login details. and somehow trigger the "start download" button and make it invisible.
I've worked out how to send command line parameters and can see how to get the software to do something different if it hears /silent but how do I hide the forms?
I'm lost.
any help would be much appreciated!
C# still has a Main() function. In a standard winforms solution, all it does is create your Form1 (or whatever it gets renamed to), and start the application event queue with that form.
For example, it should look something like:
public static void Main()
{
Application.Run(new Form1());
}
Modify this function. If you see command line arguments, do whatever you have to. If there are none, let it do its normal magic with the form. When you're done, it would be something like:
public static void Main(string[] args)
{
if (args.Length > 0) {
// log in
// do all the necessary stuff
} else {
Application.Run(new Form1());
}
}
Modify the Main method which should be the entry point to your application. If there are any arguments, you don't need to instantiate and show any forms, just run the code to do your job without UI.
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0)
{
// silent mode - you don't need to instantiate any forms
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
find static Main method in your solution. Inside that method you will have Application.Run(new Form()) or (form.Show() or ShowDialog()). So they key is to pass a parameter that will tell you now to call this method (Show method on forms)
The key is to have your business logic in a class that is independent of you form and use this class when you want to have GUI or when you want scheduled task
I answered this just other day -- on this question
Pay attention to the difference between code blocks -- the first block runs formless, the 2nd block is standard.
if (ABCFile > 0)
{
var me = new MainForm(); // instantiate the form
me.NoGui(ABCFile); // call the alternate entry point
Environment.Exit(0);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
Hey I am fairly new to the c# programming language and have enjoyed my experience so far. I normally develop applications in java but a need for the win32 library has lead me to c# so far the languages seem relatively similar. however a problem I am having at the moment is a simple piece of code that can be best explained in this example
I am trying to print a piece of string to console then display the windows form then print another piece of string to console. however the result i get is first string is printed then the form is displayed, i then have to close the form before the last string is printed. the question i would like to ask is is there anyway to get this working so the second print to console is displayed immediately after the form is displayed. im guessing it has something to do with threading but I am not entirely sure how to implement this
The solution is quite simple:
Just create a Windows Forms Application (when creating the project - which you probably did) and then go to Properties (in context menu "Project", it's the last item) and set "Output type" to "Console Application". The forms will work as before and furthermore the application will now open the console too. You can then freely write to or read from the console.
static class Program
{
[STAThread]
static void Main()
{
Console.WriteLine("first string");
var form = new Form1();
form.Show();
Console.WriteLine("the second string");
Application.Run();
}
}
It sounds like you want to be able to output messages to the console while the form is being displayed, correct? The basic issue is that as long as the form is visible, there must be a message loop running, handling events for the form. The message loop is inside Application.Run, so once you call it, it won't return until the form is closed (as you discovered).
So if you want to write to the console while the form is visible, you have a couple of options. One, as you mentioned, is to use multiple threads. Let your main thread run the message loop, and start up a second thread to write to the console. But that's not necessary--you can also write to the console from within an event handler, directly or indirectly. There's nothing wrong with doing a Console.WriteLine from within a button click handler. Or you can have your button handler call a method in your Program class, and do the writing there.
As for which solution is better, it would help to know more about what you're trying to accomplish. I assume that you don't just want to write stuff to the console--what else is it that you want to do while the form is being displayed?
My suggestion would be to start with a Console application. You can always open a WinForm from a console application...which would give you exactly what you're looking for. (you might want to think about multi-threading as well.
Hey everyone thanks for your answers I made some progress with what im trying to achieve but im not sure how correct or thread safe it is here is the code i got to run
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Project1
{
class Class2
{
[STAThread]
static void Main()
{
Console.WriteLine("hello");
Class2 t = new Class2();
t.test();
Console.WriteLine("second string");
}
public void test()
{
Thread t = new Thread(new ThreadStart(StartNewStaThrea));
t.Start();
}
private void StartNewStaThrea()
{
Application.Run(new Form1());
}
}
}
pls let me know what you think of this solution
I know this is a super-old question, but I'm going to answer in hopes of karma. One interesting work-around that works well for this comes up if you're using Visual Studio (which is a fairly safe assumption). If you start a forms project in C# in Visual Studio, then make your appropriate forms, but then change the project type to a console application (by right clicking the project-->properties-->Console Application), it will still spawn your forms, but will also keep a Console open, now all you need to do is put one Console.Write statement before your form is created, and the other after, and maybe add a flush statement!
are you using form.showDialog() or form.show()?
form.showDialog() will block until the form is closed, while form.show() will not.
I would either start with a console app, and run the application from the static main function. This is from memory - I haven't had to mess with Winforms for years:
[STAThread]
static void Main()
{
Application.Run(new YourMainForm());
}
or
I would redirect Console.Out and shove that stream into a some sort of control like a text box or list box. This is a lot of code but doable... I have written this before for on-site debugging but don't have the code handy.
Why don't you just create a new windows form with multiline textbox and dock it to the form, set BackColor as Black ForeColor as White and create a public method to send text to that textBox.
If your aim is a one Form application this works pretty much brilliantly.