What's the use of System.String.Copy in .NET?

前端 未结 8 977
误落风尘
误落风尘 2020-12-13 07:58

I\'m afraid that this is a very silly question, but I must be missing something.

Why might one want to use String.Copy(string)?

The documentation says the me

8条回答
  •  臣服心动
    2020-12-13 08:53

    In addition to what tvanfosson said (I don't think you can access the buffer used by a managed string from unmanaged code... I know it would be difficult, at least), I believe there may be a difference if the string is used as the object to do a lock on for multithreaded functionality.

    For instance...

    using System;
    
    public class Class1
    {
        string example1 = "example";
        string example2 = example1;
    
        public void ExampleMethod1()
        {
            lock (example1)
            {
                Console.WriteLine("Locked example 1");
                //do stuff...
            }
        }
    
        public void ExampleMethod2()
        {
            lock (example2)
            {
                Console.WriteLine("Locked example 2");
                //do stuff
            }
        }
    }
    

    I believe if the two example methods are run in parallel, they will be locking the same object and thus one will not be able to execute while the other is inside its lock block.

    However if you change it to this...

    using System;
    
    public class Class1
    {
        string example1 = "example";
        string example2 = string.Copy(example1);
    
        public void ExampleMethod1()
        {
            lock (example1)
            {
                Console.WriteLine("Locked example 1");
                //do stuff...
            }
        }
    
        public void ExampleMethod2()
        {
            lock (example2)
            {
                Console.WriteLine("Locked example 2");
                //do stuff
            }
        }
    }
    

    Then I believe they will only block execution of other threads executing the same method (i.e. any threads executing ExampleMethod1 will be locked until each completes, but they will not interfere with threads running ExampleMethod2).

    Not sure this is a useful difference, since there are better mechanisms for synchronization (I don't think locking strings is a very good idea).

提交回复
热议问题