Thread method skipping 'if' statement [closed] - c#

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 7 years ago.
Improve this question
When I try to use my method in created thread, thread skips 'if' statement in a loop. The problem is label4 is always shows else state. What should I do for the right operation? Here is my code;
This is where I create threads;
for(int i = 0; i <threads; i++)
{
var tempThread = new Thread(new ThreadStart(DoWork));
tempThread.Name = i.ToString();
tempThread.Start();
}
CheckForIllegalCrossThreadCalls = false;
And this is what my thread method do;
public void DoWork()
{
for(int i=2; i < variable/ 2; i++)
{
if (variable% i == 0) label4.Text ="yes not";
else label4.Text = "yes";
}
}

I'm guessing this is what you want to do, but since you haven't told us your goals we can only guess
public void DoWork()
{
for(int i=2; i < variable/ 2; i++)
{
if (variable% i == 0) {
label4.Text ="yes not";
return;
}
}
label4.Text = "yes";
}
I don't use C# but if DoWork is how you create a Thread then I think it's a bit much for something that should take almost no time at all to finish.

Related

Close all active window and open new one [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 2 years ago.
Improve this question
I make some application then i need function for close all active window in c#
but i need to open new one after that
so my code is..
for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
App.Current.Windows[intCounter].Close();
Dashboard mf2 = new Dashboard();
mf2.mastersupplier_clicked(sender, new RoutedEventArgs());
mf2.ShowDialog();
but my application is exit and never show the dashboard dialog back.... any idea about this? im stuck in this function,.
i make this with wpf c#
Set the ShutdownMode of the App to ShutdownMode.OnExplicitShutdown before you close the windows:
App.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
App.Current.Windows[intCounter].Close();
Dashboard mf2 = new Dashboard();
mf2.mastersupplier_clicked(sender, new RoutedEventArgs());
//shut down the app explicitly when the dashboard dialog is closed:
mf2.Closed += (ss, ee) => App.Current.Shutdown();
mf2.ShowDialog();
test this code
Dashboard mf2 = new Dashboard();
mf2.mastersupplier_clicked(sender, new RoutedEventArgs());
mf2.Show();
for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
{
var wnd = App.Current.Windows[intCounter] as Window;
if(wnd != mf2)
{
wnd.Owner = mf2;
wnd.Close();
}
}

The Code Won't Execute all [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 5 years ago.
Improve this question
I have the following code:
private void G1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
decimal quantity = 0, cost = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["Cost"].Value.ToString(), out cost))
{
decimal price = quantity * cost;
G1.Rows[e.RowIndex].Cells["Total"].Value = price.ToString();
}
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity))
{
newtotalstock = totalstock - quantity;
G1.Rows[e.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
return;
}
decimal avai = 0, newavai = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai - quantity;
G1.Rows[e.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
return;
} }
The problem is, it only execute 2 out of 3 the code, I mean, when the newtotalstock is calculated, the code will end.
I try to change the newavai to up above, and the result is the same, it will calculate the newavai and pass the newtotalstock. I dont know why, all the code are correct. Please help
word "return" ends function, if you are using void type method you don't really need to use return, unless you want to quit it at certain point. The code after "return" will never be executed (only exception might be during usage "yield return", but that is another story).
void someMethod()
{
doSomething();
return;
StartWorldWarThree(); //no waries, this will never be executed :)
}
Furethermore you can always make a breakpoint in your code (click on the left border of your window, or just read about it) and then check how your code is being executed :) F10/F11 to make step in your code, F5 to go to next breakpoint or end execution, if there are no more breakpoints.
Taking in count that all conditions are true the return; will stop executing the rest of the code, if you want the 3 if to be executed, remove the return; and place it the last line of the method as
void Method() {
if() {}
if() {}
if() {}
return;
}
Or dont place it at all, because that method is void and does not need it

Why the class instance value is corrupted in the multi-thread environment? [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 years ago.
Improve this question
Here is the simple code,
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Thread thread = new Thread(new ThreadStart(()=> SimpleClass.Instance.weird.SetHello(i)));
thread.Start();
}
Console.Read();
}
}
interface IClass
{
WeirdClass weird{ get; set; }
}
class SimpleClass : IClass {
public static SimpleClass Instance = new SimpleClass();
public WeirdClass weird{ get; set; }
public SimpleClass()
{
weird= new WeirdClass();
}
}
class WeirdClass
{
public int hello;
public void SetHello(int i)
{
this.hello = i;
Console.WriteLine(this.hello);
}
}
We could see the 'hello' value in WeirdClass is not correct in multi-thread, the value is just like a static instance, but it is not.
Maybe the magic happens on SimpleClass.Instance.async, so could anyone give me some explanation about that ? Thanks
I upvoted your question since it brought me to some interesting research.
In the for loop assign the i variable to a temp ii and use ii in the thread initialization, like this:
var ii = i;
Thread thread = new Thread(
new ThreadStart(()=> SimpleClass.Instance.async.SetHello(ii)));
thread.Start();
I've tested it with different configurations and different contexts (for example, put a random Thread.Sleep between hello assignment and Console.WriteLine).
What my solution gets is this: every thread has its own unique i and gets it written on the Console a single time.
But the numbers are not written in order, since the threads don't start sequentially as you create them.
Just a side-note: as #JonSkeet recommended, don't use async as identifier, it's a reserved word. Use instead AsyncWeird, InnerClass, HelloContainer, or whatever that is not an official C# token, otherwise your code becomes less clear.
UPDATE - SOLUTION:
This:
for(int i = 0; i < 10; i++)
is equivalent to this:
int i;
for(i = 0; i < 10; i++)
That is, in both cases i is created outside the for loop, and so it is somehow shared between different cycles of the loop. If you check the link #CodeCaster provided, you'll see the same issue with the foreach loop with previous versions of C#.
If you declare the thread in a cycle with i as input, you're telling to the thread: "ok, when you start, get the i value!". In that moment, i has the proper value, but the thread asks for i only when it's effectively started, so the value has already changed because in the meantime the main thread has already begun a new cycle of the loop and has already re-assigned the i for the next iteration.
Instead, if you create a temp variable ii inside the loop, it remains in that cycle and cannot be seen outside.
This is a demonstration of the whole game: try to declare ii outside of the loop... the behavior is again the incorrect one, that you showed with the i variable.

Can't stop a timer in 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 want the timer to stop when the ImageNumber is equal to zero.
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
if (ImageNumber1 < 20)
{
ImageNumber1++
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
}
If I add a return statement after the first if statement the second if statement is disabled.
I want the timer to stop when the ImageNumber is equal to zero.
You appear to already know how to do this, assuming Health_Regen is a Timer then:
Health_Regen.Enabled = false;
Will disable your Timer.
If I add a return statement after the first if statement the second if statement is disabled.
That is to be expected as you are using the return keyword which will prevent anything after it within the same code block from being executed.
Your question does not make exactly what you are asking clear, however, I am assuming from your comment that the second if statement is not executed that you want to update the HealthBar.Image value even if the Timer is disabled? If so then something like below should work for you
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
{
Health_Regen.Enabled = false;
}
else if (ImageNumber1 <= 20)
{
ImageNumber1 += 1;
}
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png";
}
You should just be able to call the Stop method on the timer instance.
if (ImageNumber == 0)
{
Health_Regen.Stop();
}
This is just a guess!.
Replace
if (ImageNumber1 == 0)
with
if (ImageNumber1 >= 20)
Your timer will already stop when ImageNumber1 equals 0, but it just never counts down to 0.
Also if you change ImageNumber1 to 0. It may already be running the timer which will increment it by one and skip the stopper, so pretty much the way you have it coded it's based on luck right now.
The luck happens if you change ImageNumber1 while timer is already running.
Try this:
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
else if (ImageNumber1 < 20)
{
ImageNumber1++;
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
Still the luck may still happen best you can do is stop the timer outside the timer when you make it ImageNumber1 = 0;
Best Fix:
Also a better solution is to fix your program to start at ImageNumber1 = 20 and just keep going down to 0.. when it hits 0 stop the timer.. you shouldn't make it this confusing all you will have to do is rename a few png files in a new order! instead of
1.png now it will be 20.png
2.png now it will be 19.png
and so on and so on..

Extremely confusing for-loop behaviour [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm encountering an extremely strange behaviour with this code fragment.
Normally the for Statement doesnt enter when counted to 16 but leaves.
In my case it enters with i=16 and executes the the Zero-Case which ends in an ArrayOutOfBoundsException.
This behavior is repeated every time I call foo()
Is there any explanation for this?
void foo()
{
Thread.Sleep(2000);
try
{
for (int i = 0; i < 16; i++)
{
#region Switch
(switch on 0 to 15 and do something unrelated)
#endregion
}
}
catch (Exception ex)
{
MessageBox.Show("Exception occured: " + ex);
}
}
Why not loop upto your array length?
for (int i = 0; i < array.Length; i++)
{
//Your secret code here
}
Also make sure you're not changing the value of i inside the loop anywhere.
You'll never get the exception with this code(unless you modify i inside the loop) irrespective of array Length.

Categories

Resources