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 new to winform and i can't figure out how to use the BackgroundWorker.
basically what i'm trying to do is this:
i have 1 form with 2 buttons: "Import" and "Exit" . when calling ImporButton_Click all it does is creates an HttpListener and listen to a given URL. ExitButton_Click closes the form.
the problem is when i press "Import" the form get stuck and it's in "not responding" status until someone is calling the listener and free it.
i'm trying to under stand how BackgroundWorker can help me to overcome that "stuck" problem. i don't understand how to invoke the backgroundWorker1_DoWork method
Here is my code so far:
//Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ConfigurationForm());
}
}
//ConfigurationForm.cs
public partial class ConfigurationForm : Form
{
public ConfigurationForm()
{
InitializeComponent();
UrlTextBox.Text = #"enter URL here";
}
private void ImporButton_Click(object sender, EventArgs e)
{
try
{
String urlToListen = UrlTextBox.Text;
//Invoke MyListener
MyListener.StartListen(urlToListen); //assume this is implemented
}
catch (Exception exception)
{
string errorMsg = String.Format("An exception occured = {0}", exception);
MessageBox.Show(errorMsg);
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
}
so, what now ? how do i invoke the backgroundWorker1_DoWork ???
10x to anyone who can help
You need to call this method RunWorkerAsync
backgroundWorker1.RunWorkerAsync();
If you want to pass some argument into the handler DoWork via the DoWorkEventArgs, try the second overload of RunWorkerAsync:
backgroundWorker1.RunWorkerAsync(yourArgument);
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Very new to C# and programming in general. I've run into this problem and I don't really know how to solve it. First of all, here's the code :
It says in the "if" parts of the code that random1 does not exist in the current context. Yes, I am aware that random only exists within the Button_click part because it is between brackets. The code is supposed to pick a random number between 0 and 20 without displaying it so that the user has to guess it. If the user is wrong, it shows a hint saying if the number is too high or too low. How can I fix this problem? Thanks
EDIT : It seems that I was too vague, your answers were good though. This is the full code :
public void Button_Click(object sender, RoutedEventArgs e) //random
{
Random chiffrealeatoire = new Random();
int random1 = (chiffrealeatoire.Next(0, 20));
}
private void Button_Click_1(object sender, RoutedEventArgs e) //quit
{
Application.Current.Shutdown();
}
private void Button_Click_2(object sender, RoutedEventArgs e) //veri
{
}
public void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (BoiteChiffre.Text < random1)
{
MessageBox.Show("Too low");
}
if (BoiteChiffre.Text > random1)
{
MessageBox.Show("Too high");
}
else
{
MessageBox.Show("Congratulations");
}
}
The user is supposed to write in the textbox
You've closed off your method and left out the if statement! The random1 variable is defined and declared within your method so it doesn't exist outside of it. Please move the method's closing bracket to include the if statement as well.
Also, your two if statements should really be linked together with an else if. You've declared two separate if statements so only one of them will have the else. Not wrong, just better practice to the following.
Basic structure:
public void Button_Click(object sender, RoutedEventArgs e) {
...
int random1
if(<random1) {
random1
} else if(>random1) {
...
} else {
...
}
} // <- method closing bracket
Edit: Since you've heavily modified the code provided I'll have to update my explanation.
Your issue has to do with variable scope. A variable defined within a method has local scope to that method. It's not accessible and doesn't even exist outside of it. You should be declaring your method OUTSIDE all the methods so that you can have multiple methods using it.
Basic structure:
int random1
public void methodA() {
random1 = whatever
}
public void methodB() {
if(random1) {
...
}
}
Please try the below code snippet. You need to declare the variable inside of the same method.
public void Button_Click(object sender, RoutedEventArgs e) //random
{
Random chiffrealeatoire = new Random();
int random1 = (chiffrealeatoire.Next(0, 20));
if (BoiteChiffre.Text < random1)
{
MessageBox.Show("Too low");
}
if (BoiteChiffre.Text > random1)
{
MessageBox.Show("Too high");
}
else
{
MessageBox.Show("Congratulations");
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
We are currently in the process of updating our database system and all of the files by building them(32bit-2005 VC#) to 64 bit now. Something I've come across is the leaking of data when an assignment using this.closing += new CancelEventArgs(Event Name); I've found it to be obsolete as fellow colleagues have put it and am looking for a way to switch to using the FormClosing event.
...
Old Code and Event Ex.
this.Closing += new CancelEventHandler(AssignUsers_Closing);
private void AssignUsers_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
"some event"
}
catch (Exception ex)
{
ShowException se = new ShowException();
se.ShowDialog(ex);
}
}
This is where I'd like to convert to the FormClosing Event so that windows can take care of the data leak for me rather than having to add a -= statement for each event like this to the .dispose() function.
Idea/New Code
private void AssignUserForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
*code*
// Use e.cancel to test whether to close the form or not.
}
catch (Exception ex)
{
ShowException se = new ShowException();
se.ShowDialog(ex);
}
}
Would this be a viable alternative. Any suggestions on how to make this change?
EDIT: BETTER OVERVIEW OF MY QUESTION
Changing this:
public AssignUserForm()
{
InitializeComponent();
InitMe();
try
{
Database.ApplyFieldSecurity(this);
}
catch { }
}
private void InitMe()
{
try
{
this.Closing += new CancelEventHandler(AssignUsers_Closing);
// Get the users from the system
//Binding happens
}
catch (Exception ex)
{
throw ex;
}
}
Turning it into something where I can use Windows Events to simply create a FormClosing event.
The problems were solved. There was a data leak occurring between our database and when the control that this dialog belonged to were loading. I appreciate all of the help. The database shot over the information before the dialog loaded, and then would send it over again. Only one set of the data was properly disposed of. We fixed the problem. Thank you. –
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'm writing a program on C# and I'm just starting on using Exception. I've done Java before but I tried to avoid exception at any cost. I understand now that I can't avoid it any longer. So I need some advice. I have a code like this:
try
{
//...
}
catch
{
//...
}
//...
try
{
//...
}
catch
{
//...
}
This is a GUI program. I want to make it so that if an exception is caught, the program will basically stop all operation and but not close the program, so the GUI is still there, users can make changes to the problem found.
BTW: Our lecturer will fail us for multiple returns, so that advice won't do
You can define a handler to catch all unhandled exceptions. The exact mechanism depends on the UI framework you are using.
For WinForms you can do something like
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// Windows forms exceptions handler
Application.ThreadException += new
ThreadExceptionEventHandler(Application_ThreadException);
http://kenneththorman.blogspot.com/2010/10/windows-forms-net-handling-unhandled.html
For WPF you would do something like
<Application x:Class="UnhandledExceptionHandler.App"
DispatcherUnhandledException="Application_DispatcherUnhandledException">
</Application>
private void Application_DispatcherUnhandledException(object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
// Handle the exception
}
http://www.codeproject.com/Articles/90866/Unhandled-Exception-Handler-For-WPF-Applications
Just in case Eric J.'s answer is too involved:
I assume since your prof will only permit one return statement that you will have something like a service that does some work and notifies the caller of the status and possibly an error message.
If you can get by with boolean messages, then the following should work for you:
public class Service
{
public bool DoWork()
{
bool success = false;
try
{
//code to do work
success = true;
}
catch(Exception ex)
{
//do something with the ex
success = false;
}
return success;
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to learn programming and I am starting with a book called Software Development Fundamentals. However I am having loads of difficulty understanding certain subjects. Especially because my native language is not English. I am stuck at the subject (events) and (delegates). I feel like this is to difficult for me, I can not even get this code to work!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lesson02
{
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Changed += new EventHandler(r_Changed);
r.Length = 10;
}
static void r_changed(object sender, EventArgs e)
{
Rectangle r = (Rectangle)sender;
Console.WriteLine(
"Value Changed: Length = {0}",
r.Length);
}
}
class Rectangle
{
public EventHandler Changed;
private double length;
public double Length
{
get
{
return length;
}
set
{
length = value;
Changed(this, EventArgs.Empty);
}
}
}
}
I get this error:
Error 1 The name 'r_Changed' does not exist in the current context 14 59 Lesson02
C# is case-sensitive language. You have defined function as r_changed and using it as r_Changed
Use
r.Changed += new EventHandler(r_changed);
instead of
r.Changed += new EventHandler(r_Changed);
I'm pretty sure you'd know by now that C# is a case sensitive programming language.
This should work
static void r_Changed(object sender, EventArgs e)
{
Rectangle r = (Rectangle)sender;
Console.WriteLine("Value Changed: Length = {0}", r.Length);
}
Notice how r_Changed is capitals (r_changed is what you originally defined)
I would suggest using this because it is easier to read.
There is a little typo mistake in your code. It should be r_Changed instead of r_changed in the your Event Handler.
i.e write
static void r_Changed(object sender, EventArgs e)
in place of
static void r_changed(object sender, EventArgs e)
(Remember C# is Case-sensitive)
What is main reasons for window.ShowDialog() stackOverflowException in WPF? I receive this exception after 10-20 seconds when I call:
if(myWindow.ShowDialog() == true)
{
//other stuff
}
Window is shows up and works good, but then I receive this exception.
The generic cause of an SOE like this is having an event handler whose code causes the same event to be raised again. A simple example is:
private void textBox1_TextChanged(object sender, TextChangedEventArgs e) {
textBox1.Text += "a";
}
Type a letter, takes about 5 seconds for program to run out of stack space and bomb. Your primary weapon to diagnose exactly which event handler causes this problem is the debugger, look at the Call Stack window. You solve it by using a little helper variable that indicates that you expect the event to be fired again so you can ignore it. Like this:
bool changingText;
private void textBox1_TextChanged(object sender, TextChangedEventArgs e) {
if (changingText) return;
changingText = true;
try {
textBox1.Text += "a";
}
finally {
changingText = false;
}
}
The try/finally is not strictly necessary but wise if you expect to keep your program running after an exception.
Surprisingly a stack overflow exception can be caused by repeatedly calling window.ShowDialog asynchronously.
public MainWindow()
{
InitializeComponent();
TheCallDelegate = TheCall;
_timer = new DispatcherTimer();
_timer.Tick += _timer_Tick;
_timer.Start();
}
DispatcherTimer _timer = null;
void _timer_Tick(object sender, EventArgs e)
{
_timer.Dispatcher.BeginInvoke(TheCallDelegate);
}
Action TheCallDelegate;
void TheCall()
{
Window win = new Window();
win.ShowDialog();
}
As you can see there is no actual recursion here (or there shouldn't have been) but once the exception happens you can see that the call stack is indeed full.
Without looking at how Window.ShowDialog is implemented internally I can't say what is the deeper cause of this.