|
This has been stated quite a few times, format your code (using the pre tags) or it will just get ignored.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
I'm trying to make a class that will simply put the progress bar in a loop (just to see how it works for learning purposes). I keep getting the following error though and I don't understand why.
error
Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.
here is the class code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class thread
{
private thread trd;
private ProgressBar _threadProgressBar;
public ProgressBar ThreadProgressBar
{
set { _threadProgressBar = value; }
get { return _threadProgressBar; }
}
public void startthread()
{
Thread trd = new Thread(new ThreadStart(this.ThreadTask));
trd.IsBackground = true;
trd.Start();
}
private void ThreadTask()
{
int stp;
int newval;
Random rnd = new Random();
while (true)
{
stp = ThreadProgressBar.Step * rnd.Next(-1, 2);
newval = ThreadProgressBar.Value + stp;
if (newval > ThreadProgressBar.Maximum)
newval = ThreadProgressBar.Maximum;
else if (newval < ThreadProgressBar.Minimum)
newval = ThreadProgressBar.Minimum;
ThreadProgressBar.Value = newval;
Thread.Sleep(100);
}
}
}
}
i'm calling it inside a windows form
with
public void callthread()
{
thread mythread = new thread();
mythread.ThreadProgressBar = progressBar1;
mythread.startthread();
}
thanks
|
|
|
|
|
Seems I wrote this[^] especially for you.
BTW: entering the error message in the Google search box usually leads to the solution right away.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
Just for him? Do you take requests
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Mark Nischalke wrote: Do you take requests
Not normally. I do take hints though.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
haha thanks for taking the time and writing that article just for me. I feel special
Anyway, thanks again.
|
|
|
|
|
I have form with lot's of TextBoxes and also there is a lot of threads in my program that need to read content's of those TextBoxes (settings). Since I can't access controls from other threads, I decided to make special class that will hold all the settings, and if user changes some, control will invoke OnTextChanged event and change corresponding value in class. But if I use that approach there will be a lot of similar handlers tike this
private void txtCrap1_TextChanged(object sender, EventArgs e)
{
Settings.Crap1 = txtCrap1.Text;
}
What I want is to do something like this
private void SetUpControlBindings()
{
AddBinding(txtCrap1, Settings.Crap1);
AddBinding(txtCrap2, Settings.Crap2);
}
private void AddBinding(object control, object value)
{
}
private void UpdateValue(object sender, EventArgs e)
{
if (sender is TextBox)
{
}
}
But I can't find any pointers to variables in C# Any ideas how to do this?
Actually my program is a bit more complicated. I have not only textboxes, but CheckBoxes, NumericUpDowns etc. also I want my Settings class to hold some additional objects like Lists.
P.S. I can't use reflection since my code will be obfuscated after compilation
|
|
|
|
|
Hi,
it is pretty easy to create a method that returns the Text (or any other property) of a Control, even from an unrelated thread. Look for "Retrieving information from a Control" in this article[^].
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
I can't do it because threads will read settings in a loop, much more often than settings will change. So if I'll use Invoke it will cause big performance problems.
|
|
|
|
|
then make a local copy before entering the loop, and possibly update every so often.
most of the time, my apps have several controls and a "start" button, control values only get read when "start" is clicked, i.e. the job definition is static. When it has to be dynamic, I always consider using a Forms.Timer to update a set of variables periodically, i.e. I don't invest in data bindings if I can avoid them easily.
However, if you want it truly event-driven and are willing to databind everything, that is just fine.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
Yeah, that's a good idea. I think i'll do like you saying
|
|
|
|
|
Why do you need to create several OnTextChange even handlers? One is all you need.
private void TextChanged(object sender, EventArgs e)
{
TextBoxctrl = sender as TextBox;
Settings[ctrl.Tag] = ctrl.Text;
}
private Dictionary<string, string> Settings{get; set;}
Add the tag to each textbox that will correspond the to dictionary key.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
To use dictionary for settings is a good idea, but I need to stote not only TextBox.Text but also Checkbox.Checked, NumericUpDown.Value, TextBox.Lines etc. So if I'll use dictionary it will result in lot's of type casts. Maybe you can modify your method to take this into account?
|
|
|
|
|
PomaPomaPoma wrote: Maybe you can modify your method to take this into account?
No, it's your project. If you want me to do your work email and we'll discuss rates.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Hi All,
I’m teaching myself C# and I’ve written a small application that that I use to retrieve some computer information using WMI.
The application is working and returns the information I want. My question is, because I am just learning, would someone be willing to look at my code and suggest areas where I could improve what I have written?
I’m fairly sure that there are probably better more efficient ways to do what I’ve written.
Thanks
Rob
|
|
|
|
|
If you were to show say 20 to 40 lines of it (inside PRE tags!), you likely get feedback right here.
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
Here is some of the code I used to get some BIOS info and display it.
private void SearchWMI_Data(string hostName)
{
this.listBox1.Items.Clear();
this.queueStack.Clear();
string myString = "";
string target = hostName;
long ramSize = 0;
IPAddress[] myIP = Dns.GetHostAddresses(target);
try
{
if (!this.ValidateHostInput(hostName)) return;
{
ManagementScope scope = new ManagementScope("\\\\" + target + "\\root\\cimv2");
ManagementPath pathBios = new ManagementPath("Win32_Bios");
ManagementPath pathSystem = new ManagementPath("Win32_ComputerSystem");
ObjectGetOptions obj = new ObjectGetOptions(null);
ManagementClass wmiBios = new ManagementClass(scope, pathBios, obj);
ManagementClass wmiSystem = new ManagementClass(scope, pathSystem, obj);
foreach (IPAddress theIP in myIP)
{
queueStack.Enqueue("IP Address: " + theIP.ToString());
}
foreach (ManagementObject bios in wmiBios.GetInstances())
{
queueStack.Enqueue("");
queueStack.Enqueue("=== BIOS Info ===");
try
{
queueStack.Enqueue("Manufacturer: " + bios.Properties["Manufacturer"].Value.ToString().Trim());
}
catch
{
queueStack.Enqueue("Manufacturer: Error reading status");
}
try
{
queueStack.Enqueue("SN: " + bios.Properties["Serialnumber"].Value.ToString().Trim());
}
catch
{
queueStack.Enqueue("SN: Error reading status");
}
}
while (this.queueStack.Count > 0)
{
this.listBox1.Items.Add(this.queueStack.Dequeue());
}
}
txtBoxHostName.Focus();
}
catch
{
this.listBox1.Items.Add("Unable to find the specified computer: " + hostName.ToUpper());
txtBoxHostName.Focus();
}
}
modified on Wednesday, February 3, 2010 12:27 PM
|
|
|
|
|
Hi again,
looks pretty good overall. I have a couple of remarks:
functionality & behavior
1.
Right now your code first gathers all info, then displays it. It might be more user-friendly to intertwine those actions, so you can see the info parts as soon as they are available. More on this later.
structure
2.
You might want to split the functionality into a method gathering information (maybe returning a list of strings), and one displaying the information. So you later on can more easily change one or the other. Disadvantage: you don't see anything until all has been gathered. Possible fix: make a gather method and give it a delegate, so it can report without knowing how the report is actually done (works like a function pointer in C/C++). My Sokoban article is an example, search for "Logger".
coding
3.
your overall coding style is OK.
4.
A queue is a bit of an odd choice, a simple List<string> would behave identically here. Nothing wrong though.
5.
Objects (such as those ManagementClass instances) that have a Dispose() method and are no longer needed should be disposed of. So your code should have a try-finally where the finally tests for null and disposes. This improves the memory footprint, and for some classes is needed for correct operation. Not disposing is (almost) a bug.
6.
it would be more logical to do input validation first, so move ValidateHostInput(hostName) up. Also check the textbox contents early on.
7.
in .NET one normally throws exceptions on bad inputs, rather than just returning. Only in special cases, .NET also provides a non-throwing alternative (see int.Parse and int.TryParse).
8.
I find it strange the line IPAddress[] myIP = Dns.GetHostAddresses(target); was left outside the try block.
9.
Having try-catch without explicitly specifying exception type isn't good practice. I tend to report at two levels: a functional level (which you have), and a technical level, probably providing the whole Exception.ToString() result, which is many lines, but would help the technical people to pinpoint what caused the problem.
You passed; up to the next level!
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
1. Not sure how to approach this.
2. Not entirely sure how to do this, will need to read your article.
3. Thanks
4. This was done for a few reasons,
>1. I was having problems formatting the output and
>2. I had recently finished reading the chapter on stacks….
Guess its time to go back and readdress the <string> again more especially the list<string>
5. I will need to look into the Dispose() method and will add this to the code.
6. I have moved the ValidateHostInput(hostname) to the top as suggested.
7. I do have a method that handles exceptions for bad inputs but I don’t think that this is what you are referring to.
private bool ValidateHostInput(string userInput)
{
if (userInput.Length == 0)
{
MessageBox.Show("You must enter a Host Name \n or IP Address", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
8. This was just an oversight on my part and has been corrected.
9. Yes, this would be nice to include. Yet another thing I will need to look into…
Thank you very much for great feedback
Only question now is what part to start on first?
|
|
|
|
|
you're welcome.
eeffoc42 wrote: 4. This was done for a few reasons,
>1. I was having problems formatting the output and
Huh? you create a string, enqueue it, dequeue it, and add it to the ListBox.
Creating the string and adding it to the ListBox would result in the same net result, the queue doesn't change anything here.
eeffoc42 wrote: 7. I do have a method that handles exceptions
I'm not particularly fond of MessageBox, I tend to include reporting functionality (progress, status, errors, ...) in my active form, but that is a matter of taste. I only consider MessageBoxes acceptable for the very exceptional stuff, most certainly not for progress! It is not my job to tell the computer to go and continue all the time...
eeffoc42 wrote: 1. Not sure how to approach this
eeffoc42 wrote: 2. Not entirely sure how to do this
Not tested, just indicative:
public List<string> Gather() {
List<string> list=new List<string>();
for(int i=0; i<10; i++) list.Add("string number "+i.ToString());
return list;
}
public void ShowResults(IEnumerable<string> list) {
foreach(string s in list) myListBox.Items.Add(s);
}
and
public void Gather(Action<string> reporter) {
for(int i=0; i<10; i++) {
string s="string number "+i.ToString();
if (reporter!=null) reporter(s);
}
}
public void myReporter(string s) {
myListBox.Items.Add(s);
}
public void GatherAndReportIntertwined() {
Gather(new Action<string>(myReporter));
}
both examples illustrate separation of what you gather and how you present the results.
eeffoc42 wrote: what part to start on first?
that's up to you. Most issues are minor edits, replacing the queue stuff by a delegate-based approach is the only major one. It will shorten and clarify your code a lot, especially if you create and use a simple report method; example:
public void report(string s) {
if (reporter!=null) reporter(s);
}
where reporter now is a class member that gets initialized by this.reporter=reporter; at the start of Gather() .
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that. [The QA section does it automatically now, I hope we soon get it on regular forums as well]
|
|
|
|
|
This is Gr8... I think you can post it as an article... for getting proper feed back from others.
Thanks
Md. Marufuzzaman
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.
|
|
|
|
|
|
i am arunprasath . i am working c# developer trainee . just one month before i joined . my problem is i don't know about c# environment. so any can tell me about how can i improve my c# skills.and also how can i prepare c# language
|
|
|
|
|
Several options that I use
1) College Courses - They help but sometimes the professor has a different agenda than teaching you what it is you seek to learn. What I mean is you have to adventure on your own. I found college was more about theory and concepts. Anyway, a basic c# class would get your started with understanding things like foreach, classes, so for forth and so on....
2) Online Video Training
I highly recommend this. I personally use learn visual studio dot net videos[^] They are to the point and very informative. Check it out.
3) Books are always your friend. I know my library has several books on Visual c# 2008 so check those out.
4) And of course there is always this forum to ask your specific questions. It is however best to post some of the code that you are working on so people get the idea that you are trying and are able to understand your logic and offer suggestions.
I hope this helps...
|
|
|
|
|
Since you are new you need to read and understand the rules of this community to get most from it and save yourself from being flamed or ignored.
How to get an answer to your question[^]
Review item #3. "hello every one" is not a descriptive subject.
I know the language. I've read a book. - _Madmatt
|
|
|
|