访问使用多线程相同的字符串(StringBuilder的) [英] Accessing the same string(StringBuilder) using multi-thread

查看:264
本文介绍了访问使用多线程相同的字符串(StringBuilder的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,如果我使用多线程上相同的字符串有时



该字符串将不会被取代。(我写这个记事本上这样语法可能使用System.Thread



错误)



...其他ofcourse

 类.... 
{
私有静态StringBuild集装箱=新的StringBuilder();

静态无效的主要(...)
{
container.Append(从文件中读取(长的那种));
线程线程1 =新主题(功能1);
线程线程2 =新主题(功能2);
thread1.Start();
thread2.Start();
//打印出容器
}

静态无效FUNCTION1
{
//完成计算和东西来获得对foreach $ B $阵列b的foreach(......龙环........)
{
container.Replace(本,有了这个)
}
}
//也是一样的功能,但用不同的东西。
静态无效的功能2
{
//完成计算和东西来获得对foreach
的foreach阵列(.......长循环...... ..)
{
container.Replace(本,有了这个)
}
}
}

现在有时一些元素不会被取代。
所以我的解决方法是调用不同的



方法container.Replace,并做了锁,它的工作,但它是正确的方式?

 私有类ModiflyString 
{
公共无效DO(字符串x,y字符串)
{
锁(本)
{
fileInput.Replace(X,Y);
}
}
}


解决方案

您应该锁定StringBuilder对象本身(替换功能里面):

 锁(容器)
{
container.Replace(本,有了这个);
}

或创建一个单独的锁对象:

 静态对象_stringLock =新的对象(); 

...

锁(stringLock)
{
container.Replace(本,有了这个);
}


My problem is if I use multi-thread on the same string sometime

the string won't get replace.(I wrote this on notepad so syntax may be

wrong)

using System.Thread ... Others ofcourse

class ....
{
    private static StringBuild container = new StringBuilder();

    static void Main(...)
    {
    container.Append(Read From File(Kind of long));
    Thread thread1 = new Thread(Function1);
        Thread thread2 = new Thread(Function2);
    thread1.Start();
    thread2.Start();
    //Print out container
    }

    static void Function1
    {
    //Do calculation and stuff to get the Array for the foreach
    foreach (.......Long loop........)
    {
    container.Replace("this", "With this")
    }
    }
    //Same goes for function but replacing different things.
    static void Function2
    {
    //Do calculation and stuff to get the Array for the foreach
    foreach (.......Long loop........)
    {
    container.Replace("this", "With this")
    }
    }
}

Now sometime some element does not get replace. So my solution to this is calling container.Replace on a different

method and do a "lock" which work but is it the right way?

private class ModiflyString
{
        public void Do(string x, string y)
            {
                lock (this)
                {
                    fileInput.Replace(x, y);
                }
            }
}

解决方案

You should lock the StringBuilder object itself (inside the replace functions):

lock (container)
{
   container.Replace("this", "With this");
}

or create a separate lock object:

static object _stringLock = new object();

...

lock(stringLock)
{
    container.Replace("this", "With this");
}

这篇关于访问使用多线程相同的字符串(StringBuilder的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆