1

Background: I have a list of objects that are directly linked to the UI in WPF. I need to do some work with those objects, but while I am working with them (asynchronously) I do not want any refreshes on the UI (performance and aesthetic reasons).

So I thought, I might copy the items (using Collection<T>.CopyTo(T[] array, int index)), work on the copy, then override my original list with the copied one. The problem is, that even then the reference are kept and the UI is continuously refreshed. Code example of what I did:

 MyUIObject[] myCopiedList = new MyUIObject[MyObjectsLinkedToTheUI.Count]; MyObjectsLinkedToTheUI.CopyTo(myCopiedList); foreach (MyUIObject myCopiedItem in myCopiedList) { //while I do this, the UI is still updated PerformLongAndWearyOperationAsync(myCopiedItem); } MyObjectsLinkedToTheUI.Clear(); foreach (var myCopiedItem in myCopiedList) { MyObjectsLinkedToTheUI.Add(myCopiedItem); } 

Is there a possibility to copy my items without keeping a reference to the original object?

UPDATE 1

Thank you for your contributions so far. One thing I forgot to mention: This is for Windows Phone 8.1, so ICloneable is not available.

1
  • 4
    You need to "clone" them - create new objects and copy the properties over, cloning any reference types as well if you want a "deep copy". Search for "clone" "shallow copy" and "deep copy" and you'll find something that meets your needs. Commented Mar 30, 2016 at 14:29

1 Answer 1

4

You need to clone them somehow. Either implement ICloneable interface and do all rewriting manually or you can use some hacks/tricks like serializing and deserializing object.

Flow with serialization is something like this:

  1. Take your object
  2. Serialize it to, for example, JSON, binary format etc.
  3. Now deserialize what you got in step 2 into new object

You'll have a copy of your object that way but it costs more processing power and is prone to some hard to catch errors. But it's an easy way to go. Thing with implementing ICloneable is more reliable but you need to write all that mapping by yourself.

Also, consider using structs instead of classes. Structs are always copied by value not reference. It has some drawbacks so it's up to you if they suit your usage scenario.

Sign up to request clarification or add additional context in comments.

3 Comments

You could also use a tool like Automapper when implementing ICloneable, it can cut out some of the boilerplate copying.
@CodingGorilla sure, that's one possible approach that would help speed things up for programmer but base idea is the same - either do it somehow explicit or go for some hacks/tricks. Or use structs if that meets requirements.
Does not really satisfy me, but if there is no other way... Thank you. I decided to go for the manual mapping way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.