473,758 Members | 2,340 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread class - using lock object

Hi ,

I had a doubt regarding a piece of code with me , that has to do with
System.Threadin g.Thread class .

In it user instantiates an array of Thread class and to all of them
assign a method for execution using ThreadStart Delegate say "worker"
method .

Now in the worker method there's a piece of code :

lock (typeof(<ClassN ame>))
{
try
{
Thread.CurrentT hread.Name = AppDomain.GetCu rrentThreadId() .ToString();
}
catch (System.Excepti on ex)
{
// Exception code
}
}

where as you can see there's a Synchronized region been created using
lock keyword .

However , what i think is , this is not required since , Worker method
is an instance method and every thread will execute it's own separate
method , so , there's no need , but then another point is all this code
is as a part of an exe , which has only one instance created at any
point of time , so it seems may be required even .

Any comments regarding this ?

thanks ,

Mrinal
Nov 21 '05 #1
4 2158
Mrinal,

For the code that you listed, you don't need the lock at all.

You are looking to assign to the value of the current thread, which will
be different for every thread that this routine is called on. Since that is
the case, you don't have to worry about multiple threads accessing the
value.

It should also be noted that you shouldn't use the static
GetCurrentThrea dId method on the AppDomain class anymore, since it is not
guaranteed to give you an id which corresponds to the current thread.
Threads in .NET are no longer mapped to physical threads on the machine.
They are logical entities and should be treated as such.

In general, when you are working with threads, you need to use a lock
statement to synchronize access between threads when they share a common
resource. Since you are not sharing anything here, it's a non-issue.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Mrinal Kamboj" <mr***********@ oracle.com> wrote in message
news:6N******** ******@news.ora cle.com...
Hi ,

I had a doubt regarding a piece of code with me , that has to do with
System.Threadin g.Thread class .

In it user instantiates an array of Thread class and to all of them assign
a method for execution using ThreadStart Delegate say "worker" method .

Now in the worker method there's a piece of code :

lock (typeof(<ClassN ame>))
{
try
{
Thread.CurrentT hread.Name = AppDomain.GetCu rrentThreadId() .ToString();
}
catch (System.Excepti on ex)
{
// Exception code
}
}

where as you can see there's a Synchronized region been created using lock
keyword .

However , what i think is , this is not required since , Worker method is
an instance method and every thread will execute it's own separate method
, so , there's no need , but then another point is all this code is as a
part of an exe , which has only one instance created at any point of time
, so it seems may be required even .

Any comments regarding this ?

thanks ,

Mrinal

Nov 21 '05 #2
Nicholas ,

Thanks again , but few things , i agree Thread class in .Net is a
logical wrapper , but then underlying unmanaged implementation should
correspond to OS threads , essentially , what i mean is on doing :

Thread t = new Thread(<Threads tart delegate>) ;

it should spawn a corresponding entity in the OS and on using Appdomain
static method , i should be able to get the relevant id . What are your
views regarding this .

also , what if i use :

[DllImport("kern el32.dll", EntryPoint="Get CurrentThreadId ")]
public static extern uint GetCurrentThrea dId();

so , it will be :

Thread.CurrentT hread.Name = GetCurrentThrea dId().ToString( ) ;

instead of Appdomain's static method , is it doing the same thing .

regards ,

Mrinal
Nicholas Paldino [.NET/C# MVP] wrote:
Mrinal,

For the code that you listed, you don't need the lock at all.

You are looking to assign to the value of the current thread, which will
be different for every thread that this routine is called on. Since that is
the case, you don't have to worry about multiple threads accessing the
value.

It should also be noted that you shouldn't use the static
GetCurrentThrea dId method on the AppDomain class anymore, since it is not
guaranteed to give you an id which corresponds to the current thread.
Threads in .NET are no longer mapped to physical threads on the machine.
They are logical entities and should be treated as such.

In general, when you are working with threads, you need to use a lock
statement to synchronize access between threads when they share a common
resource. Since you are not sharing anything here, it's a non-issue.

Hope this helps.

Nov 21 '05 #3
NO. You CAN NOT do this in .NET 2.0. It is not guaranteed that there
will be a one-to-one relationship between a thread id and a managed thread
in .NET.

In .NET 1.1 and before, you could do this, but it wouldn't work in .NET
2.0 and beyond, since multiple Threads can actually execute on the same OS
thread.

If you need a unique identifier for a thread, then use the
ManagedThreadId property on the Thread instance.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Mrinal Kamboj" <mr***********@ oracle.com> wrote in message
news:43******** ******@oracle.c om...
Nicholas ,

Thanks again , but few things , i agree Thread class in .Net is a logical
wrapper , but then underlying unmanaged implementation should correspond
to OS threads , essentially , what i mean is on doing :

Thread t = new Thread(<Threads tart delegate>) ;

it should spawn a corresponding entity in the OS and on using Appdomain
static method , i should be able to get the relevant id . What are your
views regarding this .

also , what if i use :

[DllImport("kern el32.dll", EntryPoint="Get CurrentThreadId ")]
public static extern uint GetCurrentThrea dId();

so , it will be :

Thread.CurrentT hread.Name = GetCurrentThrea dId().ToString( ) ;

instead of Appdomain's static method , is it doing the same thing .

regards ,

Mrinal
Nicholas Paldino [.NET/C# MVP] wrote:
Mrinal,

For the code that you listed, you don't need the lock at all.

You are looking to assign to the value of the current thread, which
will be different for every thread that this routine is called on. Since
that is the case, you don't have to worry about multiple threads
accessing the value.

It should also be noted that you shouldn't use the static
GetCurrentThrea dId method on the AppDomain class anymore, since it is not
guaranteed to give you an id which corresponds to the current thread.
Threads in .NET are no longer mapped to physical threads on the machine.
They are logical entities and should be treated as such.

In general, when you are working with threads, you need to use a lock
statement to synchronize access between threads when they share a common
resource. Since you are not sharing anything here, it's a non-issue.

Hope this helps.


Nov 21 '05 #4
Hi Mrinal,

Thanks for Nicholas's reply. I just wanted to check how things are going
and whether or not Nicholas's suggestion solve your problem.

If there is any question, please feel free to join the community and we are
here to support you at your convenience. Thanks again and have a nice day!

Best Regards,

Terry Fei[MSFT]
Microsoft Community Support
Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 24 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

31
2508
by: AlexeiOst | last post by:
Everywhere in documentation there are recommendations to use threads from thread pooling for relatively short tasks. As I understand, fetching a page or multiple pages (sometimes up to 50 but not tipical) from the Internet and doing some processing on those would be considered to be a big/long task for a thread from a pool. In our app it is possible to break the task into some small ones (thread per fetch and processing thereafter or event...
0
1237
by: Ivan | last post by:
Hi there My work on threads continues with more or less success. Here is what I'm trying to do: Class JobAgent is incharged for some tasks and when it's called it starts thread which performs the job. Application contains one list of agents that are idle at the moment and list of busy agents. In loop it checks if there are agents in idle list and if there are some, it starts them.
7
439
by: Ivan | last post by:
Hi there My work on threads continues with more or less success. Here is what I'm trying to do: Class JobAgent is incharged for some tasks and when it's called it starts thread which performs the job. Application contains one list of agents that are idle at the moment and list of busy agents. In loop it checks if there are agents in idle list and if there are some, it starts them.
8
2017
by: Senna | last post by:
Hi I have some questions about this code, http://code.doria.se/?c=18. 1. Will the Adapter class be thread-safe? 2. In the #region Way 1 I use lock(_lockobj) every time I go about and do something, is this necessary? 3. If the answer in question 2 is no, when are one suppose to use lock()? Or
2
2988
by: Gabriele Farina | last post by:
Hi, I'm tring to implement a Singleton object that should be specific for every thread who create it, not global. I tried a solution that seems to work, but I have a very poor knowledge of concurrent programming, so I'd like someone to help me find some problems in my implementation. Here is the code:
5
3805
by: admin | last post by:
ok This is my main. Pretty much it goes through each category and starts up 4 worker threads that then ask for groups to gether from. My problem is that when the thread gets done it keeps the mysql connections open so I end up with quite a few at the end. Is there a different way that I should do this? class Program { static string categories = { "emulation" , "audio" , "console" , "anime" , "xxx" , "tv" , "pictures" , "video" };
5
12247
by: Tony Gravagno | last post by:
I have a class that instantiates two Timer objects that fire at different intervals. My class can be instantiated within a Windows Form or from a Windows Service. Actions performed by one of the event handlers may take longer than the interval for either of the timers, so it's possible for multiple events to fire "simultaneously" and for events to queue up. I'm attempting to get the timers to sync on some reference type object, or use...
8
5369
by: =?Utf-8?B?R3JlZyBMYXJzZW4=?= | last post by:
I'm trying to figure out how to modify a panel (panel1) from a backgroundworker thread. But can't get the panel to show the new controls added by the backgroundwork task. Here is my code. In this code there is a panel panel1, that I populate with a lable in the foreground. Then when I click on "button1" a backgroundworker thread in async mode is started. When the backgoundworker thread completes the thread returns a panel to populate...
23
5711
by: Boltar | last post by:
Hi I'm writing a threading class using posix threads on unix with each thread being run by an object instance. One thing I'm not sure about is , if I do the following: myclass::~myclass() { : : do stuff
12
2081
by: Ronny | last post by:
Thanks Chris, Looks nice but I miss the dual way communication. In the main thread to deliver paramters and data to the worker thread- how can I do that? Regards Ronny Take a look at the background worker thread component. It has what you want built into it. http://msdn.microsoft.com/en-us/library/8xs8549b.aspx
0
9299
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10076
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9908
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8744
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6564
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3832
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3402
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2702
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.