ADO is an abbreviation of Active Data Objects. If you have to know it, I will not explain it in detail here. And "thread" --thread, I personally think is a quite professional vocabulary, and after learning the operating system, I have some real understanding. Before introducing the thread technology of ADO.NET, let me briefly explain the meaning of threads. The thread is to allow a portion of the program to run independently of other parts. Threads can run multiple operations while executing a single thread, allowing users to feel like at the same time, even if certain threads have errors, the operations between them will not be directly affected. A typical example of a multi-threaded feature is the Word spell check program in Office. At the beginning of the program, the execution pointer is at the top of the program, and then moves to the location where the read code is started. However, Word will also start another thread and create another execution pointer. When typing text, this new thread will check the text entered in the document and place it to the red wavy line mark with the wrong mistake. This is often seen when it is in English. I can't talk about the word "process", and the two words are almost always appearing. Windows can save many programs simultaneously in memory and allow users to switch back and forth between programs. This ability to run multiple programs at the same time is called multitasking. A plurality of individual threads can be included in a process. So pay attention to, multitasking and multithreading is not a matter. Since there may be many threads, you can specify different priorities for different threads. Talk to the half-day thread, let's combine it with ADO.NET. In the field of database access, threads can establish controls with large amounts of data without preventing users from interacting with other controls. .NET Framework improves the programmability of running multiple execution threads. Before introducing the asynchronous operation of ADO.NET, you must explain a few points.
1.NET Framework simplifies the work of generating threads with system .threading namespace, but this is also dangerous. Threads may cause difficult events, I think everyone has a lot of puzzling errors that occur when using multiple software under the Windows operating system. 2. Thread applications are difficult to debug, but debugging is very important, if used in banking system, medical system, abnormal errors, loss will be large. 3. Need to manage threads carefully, the threads in multi-threaded applications actually share the same memory space, and there is a possibility to cover other important data between the threads in the same process.
After knowing the above content, of course, our instance does not involve the so complicated situation, as an initiator can first introduce the SYSTEM .THREADING namespace.
System .Threading Name Space Place the main components of the multi-threaded application.
The ThreadStart agent uses the ThreadStart thread agent to specify the method name to be executed when generating the thread. The ThreadStart agent does not actually run the thread. When you need to call the start () method, the thread starts with the method specified in the thread agent. ThreadStart can look at the entry point of thread. When generating a ThreadStart object, the pointer to the method you want to run when you start execution of the thread. You can specify this value with the overload constructor:
DIM TSFILL AS System. Threading. Threadstart = new system. Threading. ThreadStart (Addressof mymethod)
The method specified as a thread agent cannot accept any parameters, that is, the MyMethod method is no function, otherwise an error will occur. If you want to specify a specific input condition, you can put the method in another class, then set the properties of this class at runtime, incoming information as method parameters. In addition, the method should be a function of the child, not the return of the numerical value. If the thread agent returns a value, it will be limited to the synchronous operation and cannot take advantage of asynchronous threads. When the subroutine is executed, the value is not returned, but an event is issued. This will tell the call to call the code returned. After setting the ThreadStart agent, you can get a new instance of the THREAD object. Thread object system. Threading. Threading object is the basic class that generates different execution threads in the application. You can use the System. Threading. Thread object and pass the ThreadStart agent to the constructor, generate a thread:
Dim twfill as system.threading. Threadthdfill = new three (tsfill)
In the above code, we are incorporated into the THReadStart agent's object to the constructor of the Thread object. There is also a method of omitting the generation of ThreadStart objects, directly incoming pointer to the method agent:
DIM THDFILL AS New System. Threading. Thread (Addressof Mymethod)
The constructor of the Thread object requires a parameter, which is a thread agent that can be passed with the ThreadStart object or the AddressOf operator.
The start () method start () method is the most important way in system. Threading namespace. This method is responsible for actually derived threads. It uses the thread agent specified in the threadStart () object to determine the specific method of the thread execution start. The start () method is used with other thread operation methods. After calling this method, you can use the ThreadStart property to monitor the state of the thread. Note: The thread can only start once. If this method is called multiple times, an exception is generated.
The CurrentThread property uses multiple threads, you might want to modify when specific threads are executed, which is to use the currentthread attribute.
Managing threads send threads and their own runs, sometimes it is impossible to meet demand, may be suspended and resume threads based on specific logic. You may have to use some of the thread security control abort the thread execution in some way errors. The Thread object provides some ways to closely control thread behavior.
1. START () Method has been described above 2. Abort () method THREAD object's Abort () method terminates the specific thread. This method is usually used with ThreadState with the IsAlive property to determine the status of a particular thread. When you call an Abort () method, the thread does not die automatically. In fact, you must also call the Join () method to complete the termination process. Even so, all FINALLY clauses in the TRY block are executed before the thread is closed. Call the Abort () method for the thread that does not start, it starts and stops. To call the ABORT () method for the suspended thread, it recovers and stops. When the thread is waiting state, blocked or hibernation, first interrupt the thread when calling the Abort () method, then abort the thread. 3. JOIN () method JOIN () method uses timeout parameters, waiting for thread death or timeout. The Join () method returns a Boolean value. This method returns true if the thread has terminated. This method returns false if it takes timeout. 4. SLEEP () Method SLEEP () method is suspended in a certain period of time. Be careful when placing the thread in a sleep mode. Do not place the threads using external resources in hibernation, such as database connections, otherwise they will be unlocked. Also, don't place the thread in hibernation, because the Windows Forms, such as the control, because the WindWOS form uses Single-Threaded Apartment (STA). 5. Suspend () Methods Suspend () method Delays the process of threads to any activity. If the resume () method is called, the process continues. Like the Sleep () method, do not pause the threads, Windows Forms, and Controls that use the database connection. It is best not to force thread pauses and recovery, but use the thread status attribute to change the behavior of the thread. Because the processing multiple threads need to take up a large number of processor resources. Thread pauses and recovery is expensive. Multiple thread pauses and recovery becomes a scenario switch. 6. Resume () Method Resume () method Continue to process the paused thread. 7. Interrupt () Method Interrupt () method The request thread stops working after leaving, sleep, or connected. The interrupt () method does not produce the ThreadAbortExcectionThreadState thread state that cannot be captured as the Abort () method. The table is the enumeration value of the ThreadState property:
Numerical value
Description
The Aborted thread is already called, but the thread has not received this information, system .threading. ThreadAbortAdAdException will terminate the thread Background thread as the background thread, thread. IsBackground property determines the thread. The Running thread is executing the stopped thread has stopped the stopRequested thread is being requested to stop the suspended thread is paused. The SUSPENDREQUESTED thread is being procedure to suspend UNSTARTEDTHREAD. The Start method has not been threaded to call the WaitSleepjoin thread at the waiting, sleep or connection status
Let's implement a very simple ADO. NET thread application: First, open Microsoft Visual Studio. Net We create a new Windows application, named ado threading, as shown:
After establishing a dual search engine to establish an application, construct two search engines. Add the following controls to the form and arrange: 2 TextBox, 2 Button, 2 DataGrid, as shown:
Empty 2 TextBox Text properties; 2 Button's text attributes are:
Search for customers by country; search for orderrs by customer
Put the first search engine into the engine of the customer according to the customer's country. First drag a SqlDataAdapter control to the form, the SqlDataAdapter control is in the DATA section in Toolbox. Then right click on the CONFIGURE DATA Adapter selected from SqlDataAdapter, then pop up the Data Adapter Configuration Wizard point next, select the database you want to connect. In this experiment, we choose the SQL Server2000 has been built Northwind database, you will be every time you begin a database. The name of the database will appear frequently.
After NEXT, select Using Existing Stored Procedures (with existing stored procedures), then select the getCustomersByCountry stored procedure in the SELECT menu in Bind Commands To Existing Stored Procedures.
Then select Finish. The getCustomersByCountry stored procedure, the Northwind database is not new, the content is as follows:
Alter procedure getcustomersbycountry @ countryname varchar (15) assselect * from customersterwhere country = @ countryname
Then generate DataSet with this DataAdapter, as shown
Name Dataset DSCUSTOMERSBYCOUNTRY1. Then set the first DataGrid's DataSource property to a new DSCUSTOMERSBYCOUNTRY1 DATASET
This first search engine is configured. Let's configure the second search engine, steps basically and configure the first search engine, no longer say it. The stored procedure is selected as SelectOrDersbycustomer, as follows:
Alter Procedure SelectOrDersbycustomer @ Customerid Char (5) Asset NoCount ON; Select ORDERID, Customerid, ORDERDATE, SHIPPEDDATE, Shipvia, FREighTFrom ORDERSWHERE CUSTOMERID = @ Customerid
The generated DataSet is named DSORDERSBYCUSTOMER1 and then configure the second DataGrid's DataSource property for DSORDERSBYCUSTOMER1 DATASET. The database is finally configured, the lower part of the form is shown below:
Next, enter the most important coding phase. First, pass the search criteria in the TextBox control to the value properties of the Parameter object of each SelectCommand. Then add code logic to the click event of each button.
Connect the national name to the selectCommand's Parameter
Private Sub Button1_Click _ (ByVal sender As System System.Object, ByVal e As. EventArgs) _ Handles Button1. Click 'Populate customers by country name Try SqlSelectCommand1. Parameters ( "@ CountryName"). Value () = TextBox1. Text Catch excParam As System. Exception Console. WriteLine ( "Error at populating parameter" & excParam. Message) End Try Try FillCustomers () Catch excFill As SqlClient. SqlException Console. WriteLine (excFill. Message) Catch excGeneral As System. Exception Console. WriteLine (excGeneral End Tryend Sub Connecting Customerid Find Conditions with SelectCommand's Parameter
Private Sub Button2_Click _ (ByVal sender As System. Object, ByVal e As System.EventArgs) _ Handles Button2. Click 'Populate orders by customer Try SqlSelectCommand2. Parameters ( "@ CustomerID"). Value () = TextBox2. Text Catch excParam As System. Exception Console. WriteLine ( "Error at populating parameter" & excParam. Message) End Try Try FillOrders () Catch excFill As SqlClient. SqlException Console. WriteLine (excFill. Message) Catch excGeneral As System. Exception Console. WriteLine (excGeneral. Message) END TRYEND SUB
FillRDERS () subroutine
Private Sub FillOrders () Try DsOrdersByCustomer1. Clear () Me. SqlDataAdapter2. Fill (DsOrdersByCustomer1) Catch excFill As SqlClient. SqlException Console. WriteLine (excFill. Message) Catch excGeneral As System. Exception Console. WriteLine (excGeneral. Message) End TryEnd Sub
FillCustomers () subroutine
Private Sub FillCustomers () Try DsOrdersByCustomer1. Clear () Me. SqlDataAdapter1. Fill (DsCustomersByCountry1) Catch excFill As SqlClient. SqlException Console. WriteLine (excFill. Message) Catch excGeneral As System. Exception Console. WriteLine (excGeneral. Message) End TryEnd Sub Ok! You can run and test each search engine first. The first search engine accepts the national name as a lookup condition, providing a list of customers belonging to the specified country. The second search engine accepts CustomerID as a lookup condition that provides orders that belong to the specified customer. However, everyone should pay attention to waiting for the first search to complete the new search. When the experiment, everyone can be fast, because the current computer configuration is very high, the search takes the time is very short, everyone can press After the lookup button quickly moves the cursor to the second TextBox, the cursor cannot be placed in the text box. At this time, you will need a thread to solve this problem.
Generate thread proxy The first search engine is handled under the country, and customer is obtained according to the country. The first thing to import System .ThReading names in order to directly reference the Threading class member. Add an Imports System .thReading statement before defining class Form1. Then you have to generate a thread agent, replace the FillCustomers () method that is directly called. Modify the second TRY block, replace the FillCustomers () method with the following code.
DIM TSFILL As ThreadStart = New ThreadStart (Addressof Clsfiller. FillCustomers)
This line code generates the ThreadStart object, passes the thread agent as a constructor input parameter to FillCustomers ().
Generate new threads with statements declare thread objects:
DIM THDFILL AS Thread
Then instantiate this thread:
THDFILL = New Thread (tsfill)
It uses the overload constructor to pass the thread agent as the jump point of the new thread. Finally, use the Start () method of the Thread object to start performing thread:
THDFILL. START ()
Generate Object Packaging Properties .NET Framework uses logical isolation supplemental physical process supplied by application domain (AppDomains). The thread in the application is run in the logical limit of AppDomains. This main thread is the main execution logic in the application process. But we derive new processes that fill DataSet, which run outside the primary application thread, so that a thread-specific object, attribute, and method cannot be accessed by another thread. The THDFILL thread first calls the thread agent of the FillCustomers () method. FillCustomers () Method manipulates the local form object, SqlDataAdapter1 and DSCustomersbyCountry1 objects. These objects are hidden in the APPDOMAINS of the form, and the external THDFILL thread cannot be accessed. To resolve this issue we can generate the packaging properties of each object in the thread. To generate an attribute to thread, you have to move the thread logic to a separate class. Right-click Ado Thream in Solution Explorer Select Add-> Add New Item.
We add a class that is Filler.vb. Move the FillCustomers () method to this class. In order to use the SQLClient. Net data provider object in the beginning of the class code. Then package the object, need to pack three objects with DataAdapter, DataSet, DataGrid. This is where we are in None in NONE, we run through the program. The following is a code for the class Filler:.... Imports System.Data SqlClient Public Class Filler Private m_dsCustomer As DataSet Private m_daCustomer As SqlDataAdapter Private m_dgCustomer As DataGrid Public Sub FillCustomers () Try m_dsCustomer Clear () m_dgCustomer DataSource = m_dsCustomer m_daCustomer Fill (m_dsCustomer) catch excFill As SqlClient. SqlException Console. WriteLine (excFill. Message) catch excGeneral As System. Exception Console. WriteLine (excGeneral. Message) End Try End Sub Public Property CustDataSet () As DataSet Get CustDataSet = m_dsCustomer End Get Set (ByVal dsInput As DataSet) m_dsCustomer = dsInput End Set End Property Public Property CustDataAdapter () As SqlDataAdapter Get CustDataAdapter () = m_daCustomer End Get Set (ByVal daInput As SqlDataAdapter) m_daCustomer = daInput End Set End Property Public Property CustDataGrid () As DataGrid Get CustDataGrid = m_dgCustomer End Get Set (Byval DGINPUT AS DATAGRID) M_DGCUSTOMER = DGINPUT END SET End Propertyend Class
Finally, let's modify the Button1_Click event, first to generate new variables indicating the Filler class:
DIM CLSFILLER AS New Filler ()
Then we set the DataAdapter and DataSet properties:
CLSFiller. CustDataAdapter = me. sqldataadapter1clsfiller. CustDataSet = me. DSCUSTOMERSBYCOUNTRY1
Here is a complete button1_click event:
Private Sub Button1_Click _ (ByVal sender As System. Object, ByVal e As System. EventArgs) _ Handles Button1.Click 'Populate customers by country name Dim thdFill As Thread Dim clsFiller As New Filler () DataGrid1. Refresh () Try SqlSelectCommand1.Parameters () = TextBox1. Text Catch excParam As System ( "@CountryName"). Value. Exception Console. WriteLine ( "Error at populating parameter" & excParam. Message) End Try Try clsFiller. CustDataAdapter = Me. SqlDataAdapter1 clsFiller. CustDataSet = Me . DsCustomersByCountry1 clsFiller. CustDataGrid = Me. DataGrid1 Dim tsFill As ThreadStart = New ThreadStart (AddressOf clsFiller. FillCustomers) thdFill = New Thread (tsFill) thdFill. Start () Catch excFill As SqlClient. SqlException Console. WriteLine (excFill. Message) Catch excGeneral As system. Exception console. WriteLine (ExcGeneral. Message) EndTynd Sub Press F5 execution program, with the last first search, can continue to use applications program. You can enter new data in the second search condition box when performing the first search. An exception will occur during actual operation because there is no code to which the higher level management thread is involved, which occurs in the thread of the form object, and writes the same memory space simultaneously. It is very difficult to truly write a good multi-threaded program. We are just a very simple "disabled" here, I hope everyone knows what the thread procedures.