Using the lock () function for a collection in the ToString () method

I came across a situation where my overridden method ToString()would use one of the collection of instances.

public override string ToString()
{
    string returnStr = "testString";

    lock (_sync)
    {
        returnStr = $"{returnStr}: {string.Join(",", _testList)}";  // where _testList is a List<string> in the class scope
    }

    return returnStr;
}

Since we are talking about a multi-threaded application, I was interested, since I would have to use the lock()method inside the body ToString()to avoid modifying the collection while my return string is generated. While I am making changes to the collection, the same object ( _sync) is blocked, of course.
But this method is used by other processes, such as Visual Studio Debugger, and who knows what else, since this method is inherited from the class itself Object.
For example: . I am afraid that this may be caused most often behind the scenes (frame or something else) and he will have to use a lock (which can lead to loss of performance), or it may cause a dead end while I am debugging a bad moment.

:
, ToString() ( .net)?

?

. , ( , ), , ToString(). , , string.Join() ToString(), .

!

+4
4

ToString, . - . , .

, a ToString , , . , List .

ToString , . , , , , . .

, , ? , , .

+1

. 2 , . List string.Join string.Format.

, , , , , . Visual Studio ToString , , ! .

, , .

+1

/ ToString()? -, ToString().

- : GetSnapshotRepresentation(), ToString() - (, id, type, something immutable ..)

ToString(), , ToString(), / .

+1

, , @DavidJ, . .

, ToString .

for(int i = _testList.Count - 1; i >= 0; i -= 2)
{
    _testList.RemoveAt(i);
}

, ToString() , . , :

for(int i = _testList.Count - 1; i >= 0; i -= 2)
{
    lock (_sync) {
        _testList.RemoveAt(i);
    }
}

: , , , . , , ToString(), ToString() , . . :

lock(_sync) {
    for(int i = _testList.Count - 1; i >= 0; i -= 2)
    {
        _testList.RemoveAt(i);
    }
}

, , , . ToString() , .

0

All Articles