|
Hi,
I have several comments on your code:
1.
identifiers are case-sensitive, but having two variables differ in casing only is a bad idea, so I do
not recommend your line i=I; . For one, you will confuse yourself, and furthermore if you
read this aloud to someone, he won't understand you at all.
Remark: nevertheless, people often have properties and local values that differ only by the casing of
their first letter, so you could have public int Something {set {something=value;}}
which is generally accepted and understood by everyone.
2.
I don't like the newThread names (both namespace and class) very much. Everything is new at first, and
gets old by itself, so I would avoid having new in such names. I would suggest "MyThread", "TestThread",
"SomeSpecialThreadDoingSoAndSo", whatever best describes it.
It may seem irrelevant, but picking appropriate names will help you as soon as you (or a team of people)
get involved in bigger projects, so I recommend taking care of this from day one.
3.
The line Thread.Sleep(1); will not behave exactly as you expect, it will typically sleep for 10 or
more milliseconds; you may want to read my timers article.
4.
To answer your specific question: the sequence
- call constructor (mainForm = new winFormApp)
- set some properties (mainForm.newThread =)
- now call a method to start something happening (Application.Run(mainForm)
is quite common, and in fact it is most often better than using a constructor or a method with a lot of
parameters.
However, I don't particularly like the idea of passing a thread to some class.
If the class is about a thread experiment, I would put all the thread related code inside the class, it
does not help having half of it in the class, and half outside.
If the class needs a thread for its own purposes (making the thread irrelevant to the outside), I would
definitely put all the thread stuff inside).
5.
I didn't like the newThreadID = new Thread(...); line much, i.e. the variable's name
should be newThread, not newThreadID, since it really is a thread (a threadID is a number identifying
a thread at the kernel level, a Thread is an instance of the Thread class).
6.
In general it is not a good idea to kill/abort a thread; it is a drastic measure to terminate it immediately,
with the disadvantage that it potentially leaves its objects in an unknown state (files open, resources
locked, whatever). So it should be avoided if possible. Here the intent seems to be to allow the app
to exit, which any foreground thread would prevent. The solution is to make it a background thread,
hence newThread.IsBackground=true; before newThread.Start();
Doing so will cause Windows to kill the background threads as soon as all foreground threads are done,
so there too the object states may be indetermined, but at exit this is of lesser importance, since
Windows will always try and clean up at exit too.
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
Thanks for the comments and input.
Responses:
1. & 2.
Comments based off the simplified example code. Sorry if I wasted your time analizing the code rather than the "general" design.
3.
timing doesn't matter, just a delay to prevent 100% CPU / thread lock if for some unknown reason the thread doesn't start right away. Which would be a case 1 out of 1000000 or more... I just need to know if it is active and running before I start up the form else trouble might start brewing
4.
You seem to have come to the same conclusion I did but with minor differences
A. I'm not passing the thread to the form but storing it's class instance in a property, which is diffrent / unheard of to me.
B. I'm more worried about what happens if form get thrown to the GC before the thread finishes, because the class instance will stay with all data intact until the GC junks it.
I've used setup properties before, which is why I thought of this. I do think this is better than running a method to get the device handles, save them to a public static ArrayList (yuck!), start the form, via onload event start processing the devices based off the public static ArrayList in a new timer thread, and then onclosing event to close the devices handles and wait for the last timer thread to die.
5.
see 1. & 2.
6.
Considering that the thread is holding handles to USB devices, I can't make it in the background. If the thread can't finish and exit within 3 seconds (~16-18 loops in the thread) after calling join() and setting the exit flag. Then it is soft locked and wouldn't matter if I killed it. Since the app is closing anyway it's ok to just junk it and the USB port handle will timeout at ~750ms via my driver. The problem here is it's better to allow the thread to finish for it might be witting to e2 on the device. Which is bad if you save to the the device and close the form before it is 100% written.
|
|
|
|
|
Hi Spacix,
you're welcome.
3.
To yield CPU cycles for the duration of the system tick, a Thread.Sleep(0) is recommended.
4,6.
You didn't tell about USB and EE before, I now see why you did what you did.
I'm still not convinced there is a need to do it this way tho, AFAIK running timers (i.e. not
stopped/disabled) and threads (foreground and background ones) remain active even if you don't
have any live references to them any more (except that the last foreground thread reaching
its exit will cause app exit). For timers it is well documented; for threads I don't know
if/where it is stated explicitly, the only thing I noticed is there is no Thread.Dispose()
so I expect the "physical" thread to live on independent of the "logical" Thread object.
7.
I would suggest you create a "myUsbDevice" class that encapsulates all relevant code,
including the thread stuff, and the dont-interrupt-EE-writing logic. You might give it an IsBusy()
or a WaitTillDone() method and give your form a FormClosing event, where you wait until
myUsbDevice.IsBusy() returns false or 3 seconds have elasped (easiest is to read DateTime.Now
in a yielding loop).
Luc Pattyn [Forum Guidelines] [My Articles]
This month's tips:
- before you ask a question here, search CodeProject, then Google;
- the quality and detail of your question reflects on the effectiveness of the help you are likely to get;
- use PRE tags to preserve formatting when showing multi-line code snippets.
|
|
|
|
|
I recently noticed that some of the code I wrote does not work as I expected; Namely, when attempting to reflectively set the value of a property on a value type, nothing happens (because it is passed to SetValue by value instead of by reference). I am wondering if there is a way to make the following set the value of the property UniqueId.
public struct foo {
...
public int UniqueId {
get { return m_Id; }
set { m_Id = value; }
}
...
}
public foo CreateFoo() {
foo rval = new foo();
PropertyInfo pi = typeof(foo).GetProperty("UniqueId");
if (pi != null) {
pi.SetValue(rval, 7, null);
}
return rval;
} I know that in the example, there is no need for reflection. However, the example is just an extreme simplification of my code to illustrate the problem. Once again, my question is, "Is there some way to modify the line 'pi.SetValue(rval, 7, null)' such that rval.UniqueId will equal 7 after the reflective call". Not using reflection to set the value cannot be implemented given the current code. Thanks in advance,
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
Got it! I have to box the object myself as follows:
public foo CreateFoo() {
object rval = new foo();
PropertyInfo pi = typeof(foo).GetProperty("UniqueId");
if (pi != null)
pi.SetValue(rval, 7, null);
return (foo)rval;
} Hope this helps someone else!
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
And that worked? I tried
foo rval = new foo();
object item = rval ;
pi.SetValue( item, 7, null) ;
and it was no better.
I just tried your way and I see it works.
|
|
|
|
|
Huh, that is odd. The documentation doesn't say it won't work for structs, the closest statement to that is:
"
To use the SetValue method, first get a Type object that represents the class.
"
Does this mean it only works for classes?
|
|
|
|
|
Well, technically it IS setting the value, the only problem is that it is setting the value on a copy of the struct passed in, so the changes are lost the instant the SetValue method returns. Oh well, at least I got it to work. Thanks,
Sounds like somebody's got a case of the Mondays
-Jeff
|
|
|
|
|
I was looking for a program that would output to the port and found Levent Saltuklaroglu’s I/O Ports Uncensored - 1 - Controlling LEDs with Parallel Port. It’s a great program, works nice.
I've been playing with the source code he uploaded with it to get a slightly different outcome from some of the buttons. Turns out, I haven't been able to compile it, not even his original code. I get an error message "missing partial modifier on declaration of type 'led.form1'; another partial declaration of this type exists". I was hoping someone could help me with this.
I'm using Microsoft Visual Studio C# 2008 express edition. I've also copy and pasted his code into a new Windowsformapplication1 window.
Is there a better way?
|
|
|
|
|
highly doubtful his project was written in 2008, probably 2003, before partial classes existed. Sounds like VS2008 has created the partial class for control autogenerated code, try just adding the word 'partial' before the word 'class' ( or perhaps after ) and see if it compiles.
Christian Graus - Microsoft MVP - C++
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
Hi
I have problem with data table in C#.In the code below i have data table which contains some values. "dt" is DataTable object and "dr" is DataRow[] object. when i fire some query on datatable using select method, it returns some datarows which fulfill the expression. And when i modify any column value of datarow like column "ID" it also modifies the values in datatable dt.
Can you tell me why this is happening? I don't want to modify values in datatable dt.
Thank you.
Class prog
{
static void Main(string[] args)
{
dr = dt.Select(expression);
dr[0]["ID"] = 10;
}
}
|
|
|
|
|
dalbhide bipin,
The datarow references the datatable, so they are "one". Why are you trying to only edit the datarow and not the table? eg: What are you doing?
Regards,
Gareth.
|
|
|
|
|
|
I am instianting an array of MyControl but after instianting my mc[0] is null. I don't understand it. shouldn't it has Width 100 and Height 100
MyControl[] mc = new MyControl[5];
public class MyControl:Control
{
public MyControl()
{
this.Width=100;
this.Height=100;
}
}
Thanks
|
|
|
|
|
You've instantiated an array to hold 5 MyControl s. You still have to instantiate the controls and add them to the array.
/ravi
|
|
|
|
|
try
MyControl[] mc = new MyControl[5] { new MyControl(), new MyControl(), new MyControl(), new MyControl(), new MyControl() };
that will allocate an array of MyControl instances and then also initialize the array slots.
Silence is the voice of complicity.
Strange women lying in ponds distributing swords is no basis for a system of government. -- monty python
Might I suggest that the universe was always the size of the cosmos. It is just that at one point the cosmos was the size of a marble. -- Colin Angus Mackay
|
|
|
|
|
hi to all.
I m creating website blocker and i don't have any idea that how to this.
can anybody send me information about this or link in C# or any algorithm
thanks to all
|
|
|
|
|
One way to do this is to programatically edit the hosts.txt file, althought that's a really cheesy solution.
A better way would be to intercept network traffic (like a firewall) and selectively allow connections. Or, you could leverage the Windows firewall - see this[^] article.
/ravi
|
|
|
|
|
Mahmood Abbasi wrote: hi to all.
I m creating website blocker and i don't have any idea that how to this.
can anybody send me information about this or link in C# or any algorithm
thanks to all
Why would we do that? You need to learn how to break the problems down for yourself - you need to be able to analyse items and do research for yourself. If you don't have any idea how to do this, why would you want to tackle such a complex area? I'm not asking this to be nasty - I'm just curious as to why you're wanting to do this.
|
|
|
|
|
well u said that if it is difficult then y r u doing this. SO friend if this was not difficult then y i aske people for help .
And about ur second question so i must do this,because i m student and its my semester project . So its unable to leave it.
How to block network IP's or Web site in C# if anybody knows or any body have some peace of code send me .
thanks 2 every body.
|
|
|
|
|
Please learn English. ur is not a word.
If it's your semester project then either you chose it, and should have chosen something you knew how to do, or you were given it, in which case you have materials to tell you how to do it. We'd love to help if you have specific questions, but not if you want to be told how to do your project from the top down.
Christian Graus - Microsoft MVP - C++
"also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )
|
|
|
|
|
look at http://www.privoxy.org/
It's not C#, but it'll get you something to look at to get an idea of where to start.
Good luck.
Silence is the voice of complicity.
Strange women lying in ponds distributing swords is no basis for a system of government. -- monty python
Might I suggest that the universe was always the size of the cosmos. It is just that at one point the cosmos was the size of a marble. -- Colin Angus Mackay
|
|
|
|
|
All of us have probably ran into this before. You disable a control for some reason or another and would like to let the user know what they did to make this control turn grey or what they can do to enable it again. Sadly, doing it with a tooltip in one or two lines of code is right out because the OnMouseEnter method checks the ButtonBase state for certain flags before rendering the tool tip.
I tried dancing with this problem today by overloading the CheckBox control and forcing the OnMouseEnter function to fire. I realized, then that I had to overload ButtonBase as well.
Not wanting to rewrite an entire class in the framework, I decided to use the old fallback of using the MouseMove event and checking its location.
That was my solution for this today. Anyone ever find a better solution? I hear WPF has built in support for this sort of thing.
|
|
|
|
|
Tooltips seem to render fine for me on disabled controls.
/ravi
|
|
|
|
|
Hmm, are you running 3.0? If so, that's one more reason to migrate.
|
|
|
|
|