Thread name not displaying in Thread.currentThread.Name [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 8 years ago.
Improve this question
In the code below, in the second Console.WriteLine command, it fails to print the thread name. Can someone tell me why?
public class Retailer
{
public void retailerFunc()
{
ChickenFarm chicken = new ChickenFarm();
for (Int32 i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Int32 p = chicken.getPrice();
Console.WriteLine("Store{0} has everyday low price: ${1} each", Thread.CurrentThread.Name, p); // Thread.CurrentThread.Name prints thread name
}
}
public void chickenOnSale(Int32 p)
{
// order chickens from chicken farm – send order into queue
Console.WriteLine("Store{0} chickens are on sale: as low as ${1} each", Thread.CurrentThread.Name, p); // Thread.CurrentThread.Name cannot print a name
}
}

Has your application set the thread name? The default value of Thread.Name is null. I'm guessing at the point chickenOnSale is called, the current thread does not have a name.
And for future reference, MSDN does have an article on how to set a thread name. You can only set it once; any subsequent attempts to set the Thread.Name property result in an InvalidOperationException.

Related

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

Is there any difference in Console.WriteLine("{0}, var); and MessageBox.Show("{0},var) [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
Is there any error in the following statement?
var str = "Hello how are you.";
MessageBox.Show("{0}",str);
My problem was in the following code where I was not getting it correctly. The code below is part of learning process. In the MessageBox the 'designation' variable is not coming as I stated above! I originally posted it due to my ignorance that when I test something I can use the MessageBox like Console.WriteLine().
abstract class Employee //Abstract class
{
public virtual void WhichCoEmployee()
{
MessageBox.Show("I am employed in XYZ Corporation as its {0}", designation); //My problem was in this line.
//designation varaiable was not received in
//placeholder {0} for display in MessageBox.Show.
}
public void Designation(string desig)
{
designation = desig;
}
public string designation { get; set; }
}
class CEO : Employee //Inheritance
{
public void Name()
{
MessageBox.Show("My name is Satheeshkumar K");
}
}
private void button2_Click(object sender, EventArgs e)
{
CEO ceo = new CEO(); //Initializing the CEO class.
ceo.Name();
ceo.Designation("CEO");
ceo.WhichCoEmployee();
}
Subsequenly I have rectified the MessageBox.Show problem by changing the
the Message Box code.
MessageBox.Show("I am employed in XYZ Corporation as its " + designation);
That worked fine. I have nothing more to say on this. Being a member of the stackoverflow has really helped me to learn some things due to the help from other members.
EDIT:
Simply change
MessageBox.Show("I am employed in XYZ Corporation as its {0}", designation);
to
MessageBox.Show("I am employed in XYZ Corporation as its " + designation);
BTW, you need to call this method somewhere for the code to run!
No. Your two lines seems to be perfectly correct according to the syntax.
But it seems that what you are trying to achieve is something different than what you have done.. Here's the thing: You just called this overloaded version of Show method of MessageBox class, which accepts two strings.
public static DialogResult Show(string text, string caption);
Hence in your case, a message box with "{0}" text and "Hello how are you." caption will be shown.
However, Console.WriteLine("{0}", var); is completely different. It is used to print output to the console. It also has many overloaded varieties, and in this case, it will replace {0} with the value of var variable. Hence, "Hello how are you." will be outputted to the Console.

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.

Function won't return any value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
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.
Improve this question
I have a problem that I think might be really easy to solve but since I'm a C# noob I can't understand what I'm doing wrong. I have two functions: addValues() and showMessage(). My problem is in addValues(). I have two MessageBox that show exactly what they're supposed to show, but in the showMessage() function the values are not being received, it always tells me that the day and dias.Count are 0. What am I doing wrong? Thank you!
On Form1:
public List<Despesas> dias = new List<Despesas>();
public struct Despesas
{
public double transportes;
public double alimentacao;
public double vestuario;
public double agua;
public double luz;
public double educacao;
}
On Class Management:
class management : Form1
{
int day=0;
public double addValues(double transportes, double alimentacao)
{
Despesas dia = new Despesas();
try
{
dia.transportes = transportes;
dia.agua = agua;
dias.Add(dia);
}
catch
{
MessageBox.Show("Error", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
MessageBox.Show("Count " + dias.Count);
day++;
MessageBox.Show("" + day);
return day;
}
public void showMessage()
{
MessageBox.Show("Day " + day);
MessageBox.Show("Count: " " + dias.Count);
for (int i = 0; i < day; i++)
{
MessageBox.Show("Agua: " + dias[i].agua + "\nTransportes: " + dias[i].transportes);
}
}
In the comments, you mention that you actually have two instances of the management class.
Changes to one instance of an object do not propagate to other instances of that object (unless it was modified on a static member, but thats a bit different).
This holds true even if you modify a base class member, as your code does. This is because instantiation of a derived class also instantiates a new base class object.
The solution is to just use one management object instance, and pass it around as needed. You do this just like any other type:
public void Foo(management myClass)
{
...
}
A few other notes:
management is not a very good name for a class, as its not very descriptive. Also, class names in C# should be PascalCase, so it should be Management
Inheritance is probably not the right relationship between management and Form1. Is management really a "type of" or "is a" Form1?

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