Let's talk about the small program I wrote to back up my Sina Blog .. When I click the backup button, if no thread is needed .. The form may be suspended. It makes users feel uncomfortable .. How can this problem be solved ??
You may find this simple. Just a few lines of code.
Define methods
Public void mytest ()
{
For (INT I = 0; I <100; I ++)
{
This. textbox1.text = I. tostring ();
}
}
Private void button#click (Object sender, eventargs E)
{
Thread mythread = new thread (mytest );
Mythread. Start ();
}
Sorry.
An unhandled exception of Type 'System. invalidoperationexception' occurred in system. Windows. Forms. dll
Additional information: The Inter-thread operation is invalid: It is accessed by a thread that does not create the control "textbox1.
Solution:
1. Define Delegation
Delegate void mydelegate (int I );
Mydelegate = NULL;
2. Define a method to display messages
Public void showmessage (int I)
{
This. textbox1.text = I. tostring ();
This. progressbar1.value = I;
}
3. Define methods to drive messages
Public void myevent ()
{
For (INT I = 0; I <100; I ++)
{
Thread. Sleep (100 );
This. begininvoke (mydelegate, new object [] {I });
}
}
4: Run
Private void button#click (Object sender, eventargs E)
{
Mydelegate = new mydelegate (showmessage );
Thread mythread = new thread (myevent );
// Whether isbackground is in the background
// This attribute is very important. If thread isbackground is equal to false
// When the thread is not finished, you click the close button.
// Will throw an unhandled exception
// Of Type 'System. invalidoperationexception'
// Occurred in system. Windows. Forms. dll exception
Mythread. isbackground = true;
Mythread. Start ();
}
All code:
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;
Using system. Threading;
Namespace winfromtheadtest
{
Public partial class form1: Form
{
Delegate void mydelegate (int I );
Mydelegate = NULL;
Public form1 ()
{
Initializecomponent ();
}
Private void button#click (Object sender, eventargs E)
{
Mydelegate = new mydelegate (showmessage );
Thread mythread = new thread (myevent );
// Whether isbackground is in the background
// This attribute is very important. If thread isbackground is equal to false
// When the thread is not finished, you click the close button.
// Will throw an unhandled exception
// Of Type 'System. invalidoperationexception'
// Occurred in system. Windows. Forms. dll exception
Mythread. isbackground = true;
Mythread. Start ();
}
Public void showmessage (int I)
{
This. textbox1.text = I. tostring ();
This. progressbar1.value = I;
}
Public void myevent ()
{
For (INT I = 0; I <100; I ++)
{
Thread. Sleep (100 );
This. begininvoke (mydelegate, new object [] {I });
}
}
Private void button2_click (Object sender, eventargs E)
{
//
}
}
}
Click to download source code