Prev: Multiple Concurrent TCP/IP Clients
Next: Exception handling in unManaged code when being called from managed code
From: Peter Duniho on 29 Apr 2010 02:34 Michal wrote: > [...] > To answer Peter's question: >>> In general, classes like that are not thread-safe. Why do you think > yours should be? > > Generally my program constantly generates some graphical data for other > input devices in separate thread and it allows user to change them anytime. > So I need thread safe access to edit and generate methods of different > classes. Non-sequitur. The fact that you need thread-safe access to the data doesn't mean that the data types themselves need to be thread-safe. The List<T>, Queue<T>, and many other .NET classes are not thread-safe, and yet I use them in a thread-safe way in multi-threaded code on a regular basis. The same thing can be true for your own types. That said, you seem set on doing things the hard way, so I suppose that will have to do. Pete
From: Michal on 30 Apr 2010 01:12 Peter, I don't think it's safe to e.g. add some item in one thread to List<Whatever> and to read all the items from this List<Whatever> in another thread (that's what I do). So I'm sure, it's required to use thread safe access to my ClassToChange.
From: Peter Duniho on 30 Apr 2010 01:27 Michal wrote: > Peter, I don't think it's safe to e.g. add some item in one thread to > List<Whatever> and to read all the items from this List<Whatever> in another > thread (that's what I do). So I'm sure, it's required to use thread safe > access to my ClassToChange. No one, least of all me, is disputing that. The question is whether you have a need to build thread-safety into the object itself. The problem you are asking for help with is a consequence of your apparent desire to have a specific class manage the object used for locking: the class that you want to operate on in a thread-safe manner. But, if you would simply forget trying to make that class thread-safe, and instead require that clients of the class access it with their own thread-safe behavior, the problem you're asking for help with just goes away. The "lock" statement becomes completely sufficient for the need. Pete
From: Michal on 30 Apr 2010 07:24
Yes, I see your point and this discussion is really helping me. But I use this class in two different threads - one is changing it and second is using it... Anyway maybe you think about using it like this: .... lock (editedObject) { //change it } and in my second thread also lock (editedObject) { //use it } Yes, that might be possible - but also when I create attribute for the List<AnyDataClass> data e.g.: List<AnyDataClass> Data { get { return data } } But there's no way to assure object is locked, when accessing this data, is there? |