开发者

TextBox.Text.Replace() MultiThreading

开发者 https://www.devze.com 2023-03-13 19:10 出处:网络
im using a textbox and need to replace text in the textbox. the problem is that i need to replace 718 different items. I would like to put each replace into its own thread to quickenthe process but wh

im using a textbox and need to replace text in the textbox. the problem is that i need to replace 718 different items. I would like to put each replace into its own thread to quicken the process but when i do, it never replaces.

i have tried similar to the following

foreach (Match m in matchCollection)
{
ReplaceClass r = new ReplaceClass(TextBox,m,ReplaceText)
Thread th = new Thread(new ThreadStart(r开发者_StackOverflow.Replace))
th.start()
}


As Dyppl wrote in a comment you can access a form only from the thread in wich it was declared and it's running. I think that if you want to speed up the process don't replace the text in the text box but just copy the text in a temporary string , modify it (replace the matches ) and then overwrite the text in the form. So

string text = TextBox.Text
foreach (Match m in matchCollection)
{
   text = somereplacement(m,replacetext);

}
TextBox.Text = text;

Edit: As the Anthony Pegram says , it's not good to manipulate a string in such way inside a loop because the string gets created every time , but i don't know what your replace function does. A better way could be

StringBuilder text = new StringBuilder(TextBox.Text);  
foreach (Match m in matchCollection)
{
   //do something
   .
   .
   .
   text.Replace( toreplace ,replacement);

}
TextBox.Text = text.toString();

Or you can also use the functions to search and replace of regular expressions. Just don't replace over the textbox because each time you make a replacement the control has to be drawn again.


Multithreading won't really help you here, because you can't have all these threads accessing the same string to replace stuff, and the overhead of creating all these threads would outweigh any benefit anyway - Your computer doesn't have a 718 core CPU!

You're better off not using multithreading. Keep in mind that 718 replace operations might not actually be all that slow anyway, unless the string is huge.

Just do the replace operations without threading - If you want to add threading to your application, find an operation that takes several seconds, and doesn't all involve the same variable for the entire operation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号