c# - Thread not working properly -
i made program on stenography working not responding when large text files used. need implement threads it. tried below code still gave me same problem. don't know made mistake. need add progress bar, don't know add code.
private void button3_click(object sender, eventargs e) { thread mythread = new system.threading.thread(delegate() { run(); (int n = 0; n < 100; n++) { thread.sleep(50); progressbar1.begininvoke(new action(() => progressbar1.value = n)); } }); mythread.start(); } private void run() { if (this.invokerequired) { this.begininvoke((methodinvoker)delegate() { int ascii; string xor; string text = textbox1.text; if (textbox1.text != "") { bitmap bitmap = (bitmap)picturebox1.image; bitmap bmp = (bitmap)picturebox1.image; //richtextbox1.text = "\n"; byte[] asciibytes = encoding.ascii.getbytes(textbox1.text);// convert string byte[]. int x0 = 0, y0 = 0; // error checking, see if text can fit in image int imagesize = bitmap.width * bitmap.height; if (imagesize - x0 * bitmap.width - y0 < 8 * textbox1.text.length) { messagebox.show("too large"); } (int t = 0; t < textbox1.text.length; t++) { ascii = asciibytes[t]; xor = program.binlength(convert.tostring(ascii ^ 254, 2)); //richtextbox1.text = richtextbox1.text + xor + "\n"; (int = 0; < 8; i++) { // check if y0 has exceeded image width // wrap around new row if (y0 == bitmap.width) { x0++; y0 = 0; } hide(bmp, bitmap, y0, x0, i,xor); // x0, y0 current pixel coordinates // // embed message here // y0++; // move next pixel next bit } } messagebox.show("" + (text.length * 8)); } else messagebox.show("text???"); }); } } private void hide(bitmap bmp, bitmap bitmap,int y0,int x0,int i,string xor) { color colorpixel,newcolor; string pixr; colorpixel = bitmap.getpixel(y0, x0); pixr = program.binlength(convert.tostring(convert.toint32(colorpixel.r), 2)); newcolor = color.fromargb(convert.tobyte(program.converttopixcel(xor, pixr, i), 2), colorpixel.g, colorpixel.b); bmp.setpixel(y0, x0, newcolor); picturebox2.image = bmp; } thank you.
the thing is: you're running stuff within thread, thread code run in context of ui thread because invoke using this.begininvoke. actually, parts update ui need invoked using this.invoke.
so while think multi-threaded, not.
please use this.invoke, not this.begininvoke, begininvoke need call endinvoke @ point, otherwise leak memory/resources.
how solve it? suggestion:
prepare data thread within ui thread. is: getting text text boxes, maybe images picture boxes, etc. pass thread, maybe object of state class in state parameter of parameterizedthreadstart.
then, have thread nothing related ui! no message boxes, no updating of picture boxes, nothing. update when thread ends.
if works, may incorporate status updates, called in form of
this.invoke((action)delegate() { progressbar.value = ...; } or
this.invoke((action)delegate() { picturebox.image = ...; }
Comments
Post a Comment