How to cancel properly? [closed] - c#

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'm going to create a scenario before I ask my question.
Say you have a form with a start button, then when the user presses it a message box pops up asking if they want to continue and the options are yes or no.
When the user presses no the program should stop what its doing, return to the form and clear the text boxes/combo boxes/etc.
Now here's my question, upon selecting "no" how does one go about stopping the program from going into further code? For the code to stop what it's doing and return to the form like nothing happened?
I hope I explained myself well enough...
Nevermind everyone I realised where I went wrong... Crisis averted. Thanks for all of your input however!

Normally you'll use a Modal form, means that your current method is blocked and will be blocked until the modal form returns.
You can try something like this:
DialogResult result = MessageBox.Show("Title", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.No)
return;
If you want a custom form to show as modal, you should use ShowDialog() instead of Show(), ShowDialog will block the current execution of the executing method and will setup a temporary messageloop for handling window messages.
like:
using(FormQuestion form = new FormQuestion())
{
DialogResult result = form.ShowDialog();
// check the result.
}
Check here for more information: Displaying Modal and Modeless Windows Forms http://msdn.microsoft.com/en-us/library/aa984358(v=vs.71).aspx

In general, .NET uses a cooperative cancellation model, so methods need to have a mechanism to notify that a cancellation is requested, and they need to explicitly cancel themselves.
This is handled by many portions of the framework via the CancellationTokenSource class and the CancellationToken struct.
For full details, see Cancellation in Managed Threads on MSDN.
That being said, if the method in question is using the MessageBox directly, it can just return or stop working if the result is DialogResult.No (in Windows Forms) or Window.DialogResult is unset or false (in WPF).

Related

ShowDialog() displays no data but Show() does [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
Maybe this can't be answered without context but when I use Show():
TestView test = new TestView()
{
Owner = Application.Current.MainWindow
};
test.Show();
Everything works fine, the events are fired and my textbox/comboboxes are populated with data on the test view. But when I use ShowDialog() nothing is populated. Anyone know a reason why? I want a modal window.
This is by design.
As by documentation:
When a Window class is instantiated, it is not visible by default. ShowDialog shows the window, disables all other windows in the application, and returns only when the window is closed. This type of window is known as a modal window.
Modal windows are primarily used as dialog boxes. A dialog box is a special type of window that applications use to interact with users to complete tasks, such as opening files or printing documents. Dialog boxes commonly allow users to accept or cancel the task for which they were shown before the dialog box is closed.
Thus, the ShowDialog is blocking until the window is closed.
This means that dealing with events and similar, specifically from the Owner window will not work.
If you have additional questions, please show the relevant code with the events and how you populate them.
If for some reason you need a full blocking window - it is possible; but we will need more details.

freeze app when get data from online sql server [closed]

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
my app using sql server is located on a server . my problem is a when using this app ، freeze app when get data from server !
What is your proposed solution?
It sounds like you're executing your database query from the UI thread. Perhaps, the query is being executed in a button "click" action handler?
The UI thread is a thread where UI message loop is running and processing UI events (things like button clicks, window resize etc.). If you perform a long running task in the UI thread it will prevent all other UI messages being processed until the task is finished. As a result the UI will look frozen.
Database calls are fairly slow and it's a good idea to execute them outside of the UI thread. One solution is to spin a new thread, providing a callback method to be called once the query execution was completted.
A better approach is to use async/await. You'll have to define an async method that performs a DB call. And then await for that method in your UI thread.
Please show us how you fetch the data from a database and we'll give you more details on how to implement it without blocking the UI.
Without more info here's general advice:
Execute your query on a thread (use a Task if modern), then when thread gets it's data back invoke back on main/UI thread. This will prevent your UI from locking up while querying for data.
You might also want to start a 'spinner' or a 'loading' indicator of some sort on the UI thread so the user knows to wait and doesn't go click-crazy trying to load the data again and again...
Also be sure to include some error handling in your query thread so if things go bad you can recover and alert (messagebox, write to log, whatever you need to do).

Waiting for inputs to end and only then reading the textbox [closed]

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 6 years ago.
Improve this question
Basically, I want to make a constant input reader in my form, that waits for inputs and only after the input finishes(these inputs are from an external source, specifically - a hand-held scanner) should it be read, this code works exactly how I want, because the scanner at the end of input somehow informs that it's the end of stream/line(not really sure how though):
while (true)
{
string someString = Console.ReadLine();
doSomethingWithString(someString);
}
but I don't know how to cleanly transfer it to a form application.
Any help would be appreciated.
Assuming I understand you correctly, you want to do something like this:
public void SendScansToForm(string[] scans) //pass in an array (or list, or etc.) of the scanned items
{
MyForm form = new MyForm(); //Create a new instance of the form
form.variableToHoldScans = scans; //variable (on the form instance) to pass the scan to
}
In this way, you read in all the scans, then pass them into a new instance of the form. Presumably, this could be followed with a form.Open() or display the scans to the user, or change as needed to do whatever task is required.
EDIT:
Apparently I didn't understand; if you want to port the current code to forms, you can use System.IO.Stream (as mentioned in the comments). Additionally, you will need to determine how the scanner terminates an entry. This may be with a return character \n, \r, etc. or some other method and likely changes with different scanner models.
EDIT 2 - Additional info from the comments:
In order to read input from a scanner, you need to determine what character it's passing in to terminate the input. From my limited experience, this should be carriage return, line feed, enter or something similar.
Once this has been determined, it should be trivial to implement a method that acts on the presence of this character, allowing you to process each scan as they come in.

how to make real time code in C# [closed]

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 8 years ago.
Improve this question
I want to read sms from my GSM modem.
I wrote C# code.
This code run when I click start button.
I want to my program read sms when received, not click button.
thanks.
Your program is keyed to activate when you press a button, some method is called. You need to call this method when SMS data is received instead. This could be done using threads (SMS thread and main thread showing data) although it could just as easily be done using a cycle. In pseudo code:
while (don't quit) {
display page;
check for sms data;
sleep for small time to allow other OS programs to run also;
}
This is a "tight loop" and can use excessive amounts of CPU time depending on the code of the actual steps. For a tight program loop one simple method is to apply some sort of sleep method.
There are other ways to do the same thing, visitor pattern could probably be used, threads, etc...
It seems that you are only lacking the cycle. Your programs is probably more like:
while (don't quit) {
display page.
wait for button press.
}
although that flow wouldn't be obviously apparent at first glance without studying your program flow.
If you are using triggers (the button press is probably a trigger) you can trigger on a timer that fires as often as you want (100ms, 1 second, whatever) that checks for SMS data when fired, if there is SMS data it updates the form.
Many, many ways to do this. A quick Google for "program flow" doesn't find any useful links at first glance that would explain the many ways you could do this. Perhaps looking at other's code would help. I've often searched open source repositories for code I could look at to see how someone else did something.

Event on a File Dialog c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm working in C# VS 2012. I want to be able to have an event for a FileDialog that once the user chooses a file some code is run. So it would be something like once the filedialog is closed the code will run. If anyone can lend any help that would be great.
Well, by default, showing the dialog is modal, i.e., your thread is effectively halted until the dialog is closed. So, just Show() it and any code after that call will be run after the window closes. You can get the chosen file(s) via the FileName property (or FileNames property if MultiSelect is set to true).
This is for WinForms:
using (OpenFileDialog dialog = new OpenFileDialog()) {
if (DialogResult.OK == dialog.ShowDialog()) {
// work with dialog.FileName
}
}
The FileDialog's ShowDialog method is blocking. This means that the thread it's executed and shown on will stop executing until the file has been returned. You can use the result to check if a file was selected.
This is the WPF way:
// Call the ShowDialog method to show the dialog box.
bool? userClickedOK = openFileDialog1.ShowDialog();
// Process input if the user clicked OK.
if (userClickedOK == true)
{
... your code here
}
More info: http://msdn.microsoft.com/en-us/library/cc221415(v=vs.95).aspx

Categories