|
Hello,
Recently I have been looking into threading in .NET, specifically in C#. I think I understand the necessity of using the Monitor class (or the lock statement as a shortcut) to assure that reading and writing operations on shared data are thread-safe.
I am confused, however, about using the lock keyword on static and non-static objects, especially when the variable whose thread-safety I want to assure is in a class. This is a rather vague question, so here is some code to clarify:
class MyClass
{
private readonly object locker;
private String strToProtect;
public String StringToProtect
{
get
{
lock(locker) { return strToProtect; }
}
set
{
lock(locker) { strToProtect = value; }
}
}
private int anotherPrivateObject;
public void ThreadFunction()
{
anotherPrivateObject = 0;
for(int i = 0; i < 10; i++)
{
anotherPrivateObject++;
System.Threading.Thread.Sleep(100);
System.Diagnostics.Trace(StringToProtect);
}
}
}
...
Main()
{
MyClass instanceObject = new MyClass();
instanceObject.StringToProtect = "set the string on this instance of MyClass";
Thread myThread = new Thread(new ThreadStart(instanceObject.ThreadFunction));
myThread.Start();
instanceObject.StringToProtect = "changing this string should not be a problem";
...
} Now my questions about this code are these:
1) Is this a proper way to lock an object inside a class and access it by multiple threads? (i.e. always going through StringToProtect 's public accessor?)
2) Should locker be static ? If so, why?
I think this question mainly arises from confusion about the static keyword - this confusion mainly arose from my recent investigation of threading, because many (if not all) of the examples I have seen use a static object to lock on.
Those two questions are the most important, but a third one occurs to me as well:
3) Is it wrong or bad-practice to have a thread function inside a class which is not a static function itself? Like, in my code example, the function MyClass.ThreadFunction . Is it a problem that this is not a static function and therefore can only be called when already possessing a created instance of MyClass ?
Thank you very much in advance for your time. If I have not stated the questions clearly enough, or the code sample is confusing, please let me know, I will try to rephrase or rewrite that part of the question.
Sincerely,
Alexander Wiseman
|
|
|
|
|
I don't see anything wrong with what you're doing. You use the property correctly by locking access to your field strToProtect . The lock object should be static if the field you're trying to lock is also static, but your field is an instance variable. And your thread function doesn't need to be static. It's not bad practice, it's just depends on what your requirements demand. As an instance method, that method will have access to the particular instance of MyClass .
If you want any of these things to be static, you should make them all static: the field, the lock object, and the thread method.
HTH
|
|
|
|
|
Dustin,
Thank you for the prompt response, that solves my difficulty!
Sincerely,
Alexander Wiseman
|
|
|
|
|
One thing you may want to consider is the affects of your lock on whether you have more writers than readers or the reverse for a normal environment. This[^] is an excellant article (but does not give you the code!) on various ways to perform your locks when dealing with many threads.
|
|
|
|
|
Thanks for the reference!
Among other snippets, I had been looking at this[^] excellent article, by Jon Skeet. Because of the way he does the code snippets, though, I got confused about locking on non-static objects (almost all his samples have static locking objects, though he does make reference to static vs. non-static in one place in the article). His Miscellanous Utility library[^] is also extremely useful (he provides a class that gives you the ability to have locks with timeouts).
Thanks again.
Sincerely,
Alexander Wiseman
|
|
|
|
|
how can i check if a textbox string contains numbers? and it returns true if it contains one or more.
Donkaiser
|
|
|
|
|
|
is that the right link?
Donkaiser
|
|
|
|
|
I misread your question. You'll need a regular expression. If you're only looking for integers, a regex like "[0-9]+" would be good enough. You can run that against a string and look at all the matches. Have a look here: http://msdn2.microsoft.com/en-us/library/hs600312.aspx[^]
|
|
|
|
|
If you're using .NET 2.0 use a TryParse method, such as Int32.TryParse, to see if a string contains a number. If you're using .NET 1.x, then call Int32.Parse or Convert.ToInt32 - but be sure to wrap that call in a try/catch block because if the conversion fails, an exception will be thrown.
Checking if a string contains multiple numbers, like "12 43 656 234523 24", you can use the Split method of the String class to break the input into an array of strings. Then call Parse or TryParse on each string in the array. Beware that calling Split has subtle issues if the input value has multiple spaces in a row. You might want to remove extra spaces, or some other precautionary measure, before parsing the text into numbers.
josh
|
|
|
|
|
will that work if my string is sth like "abc12def"? the check function should return true if it found a number inside a string.
Donkaiser
|
|
|
|
|
No. You can use a regular expression, or loop over each character in the string and use Char.IsNumeric() to check if each char is a number.
Josh
|
|
|
|
|
hi
i could add exe file to my vstudio solution and set build action to Embedded Resource and by working with resources i could take it to stream .
i want to run my exe .. how to that ??
My code is ::
string fullName = this.GetResourceFullName("HDCopy.exe");//i want to run this exe
Stream stream = this.asm.GetManifestResourceStream(fullName);//load my exe to memory
//How to Run My exe from Memory (Stream) ??
private string GetResourceFullName(string resName)
{
string fullName = null;
foreach (string str in this.asm.GetManifestResourceNames())
{
if (str.EndsWith(resName))
{
fullName = str;
break;
}
}
return fullName;
}
HDCopy.exe is not dot net .
|
|
|
|
|
Check out the post by Steve Hanson at the bottom of this article[^]. It shows how to extract and run a managed EXE from an assembly. I'm not sure if it will work with unmanaged EXEs, though.
josh
|
|
|
|
|
how can i search in combo box by latter ,and the first match word be the text of the combo
MD_NADA
|
|
|
|
|
Beg, borrow and steal.
See CompletionCombo in the free Genghis controls:
http://www.sellsbrothers.com/tools/Genghis/[^]
If you don't like how it handles it, you can change the code. There is a lot of learning packed into the source code available there.
|
|
|
|
|
I think you might mean "How do I get a combobox to autocomplete input based on a letter?", if so, check out the combobox.autocomplete methods. look at AutoCompleteSource, AutoCompleteMode autocompletestringcollection.
I did this on the fly, so don't copy it word for word, but this should give you an idea.
//this assumes 2 comboboxes, cbSource and cbDestination.
<br />
private void BuildCompleteList()<br />
{<br />
AutoCompleteStringCollection cityList = new AutoCompleteStringCollection();<br />
foreach(DataRow dr in myCityInformationTable)<br />
{<br />
cityList.Add(dr["CityName"]);<br />
}<br />
cbSource.AutoCompleteCustomSource = cityList;<br />
cbList.AutoCompleteCustomSource = cityList;<br />
}<br />
In addition, remember to set the cb autocompletesource property for each combobox to custom source, and autocomplete mode to either SuggestAppend, Suggest, or Append as suits your functionality needs.
Hope this helps.
//Also, code from this was paraphrased from an example on page 160 of Brian Noyes "Data Binding with Windows Forms 2.0". I figured that I wrote this example, but I used his example as a starting point. Its a great reference for all your databinding/etc needs.
|
|
|
|
|
excuse me this is not i want
i want to search in the combobox like MicroSost forms20 combobox in com componants
please clear the answer becuase i am a bigner
thanks for helping me
MD_NADA
|
|
|
|
|
Hi,
I am trying to get the User details from an active directory but the code gives me only User names. I want their entire details like....eg. - User1 Domain/Test/Test1....
Urgent help is required.
Thanks.
Pooja.
Nothing is Impossible.
-- modified at 7:22 Friday 9th June, 2006
|
|
|
|
|
The System.DirectoryServices.SearchResult class gives you all details.
After your Active Directory search, list all available properties and find the details you need:
foreach(string name in searchResult.Properties.PropertyNames)
{
Console.WriteLine("{0} = {1}", name, searchResult.Properties[name][0].ToString());
}
_________________________________
Please inform me about my English mistakes, as I'm still trying to learn your language!
-- modified at 7:44 Friday 9th June, 2006
|
|
|
|
|
Hi,
Thanks. Your reply helped me a lot. One more thing I would like to ask here. I have a textbox in which let say I enter pooja.katiyar...this is my sAMAccountName. but when I click on the search button how can I get the property name for that particular value?
Actually I am trying to build a filter. In my UI I have a textbox and button. Whatever I enter in the textbox and click on the button, it should be able to find that record if it exists!
Thanks.
Pooja.
|
|
|
|
|
Hello All!!
I have created a windows service and the problem is when I log off my system account in which the service is currently running, the service stops. Why is this so? I want my service to run independent of my system account.
Thanx in advance
regards
Mubashir
Storan Technologies (USA)
|
|
|
|
|
Is it a real windows service?
--------
"I say no to drugs, but they don't listen."
- Marilyn Manson
-- modified at 10:42 Friday 9th June, 2006
|
|
|
|
|
How can i edit a ListViewSubItem in ListView control in C#.
I have set the View property of ListView Control to View.Details.
I set the LabelEdit property to true but it only lets editing 0th index listviewsubitem.
Thanks
|
|
|
|
|
System.Windows.Forms.ListView does not support that.
Try the article search for "editable list view".
_________________________________
Please inform me about my English mistakes, as I'm still trying to learn your language!
|
|
|
|