Call WinForm in multi-thread

xiaoxiao2021-03-06  52

Teach you how to use IsynchronizeInvoke interface to call in the correct thread; and how to put HTML into the clipboard to make other programs can be used.

By Juval Lowy and Karl E.peterson

Technology Toolbox: C #, VB6, VB5, WinForms

Question: Calling Worker Thread in Multi-threads My Worker Thread, but I can't call this form in multi-threads in the document, but in fact. I often collapse when calling. How to call the method from the form from multithreading?

Solution: Each WinForm class (including Control classes) derived from the Control class is performed by the underlying Windows message and a message pump loop. Message loops must have a corresponding thread because messages sent to a Window are actually sent to creating the Window thread. As a result, even if synchronization is provided, you cannot call these processing messages from multi-threads. Most plumbing is hidden because WinForm is binding messages to the event processing method with a proxy. WinForm converts Windows messages into an agent-based event, but you must also pay attention to the initial message loop, only the thread that creates the Form can call its event processing method. If you call these methods in your own thread, they handle events in the thread instead of processing in the specified thread. You can call any ways that do not belong to messages from any thread.

The Control class (and its assignment) implements an interface defined under the System.comPonentModel namespace - ISYNCHRONIZEINVOKE, and handles the problem of calling message processing methods in multi-thread:

Public Interface IsynchronizeInvoke

{

Object Invoke (DELEGATE

Method, Object [] ARGS);

IASYNCRESULT BeginInvoke (DELEGATE

Method, Object [] ARGS);

Object Endinvoke (IasyncResult

Result;

Bool infokeequid {get;}

}

IsynchronizeInvoke provides an ordinary standard mechanism for method calls in other threads. For example, if an object is ISYNCHRONIZEINVOKE, the client on the thread T1 can call the ISYNCHRONIZEINVOKE INVOKE () method in this object. Implementation of the INVOKE () method blocks the call of the thread, which will call the package transmission (Marshal) to T2, and perform call in T2, and then send the return value to T1, and then return to the client of T1. The invoke () method is positioned in T2 in a proxy and as its parameters in an ordinary object array.

The caller can also check the InvokeRequired property, because you can call ISYNCHRONIZEINVOKE in the same thread or you can reposition it to other threads. If the return value of InvokeRequired is false, the caller can directly call the method of the object.

For example, suppose you want to call a Close method in an Form from another thread, then you can use a pre-defined MethodInvoker agent and call the Invoke method: form form;

/ * Obtain a reference to the form,

Then: * /

IsynchronizeInvoke synchronizer;

SYNCHRONIZER = form;

Synchronizer.invokerequired

{

MethodInvoker Invoker = New

MethodInvoker (form.close);

Synchronizer.invoke (Invoker, NULL);

}

Else

Form.close ();

IsynchronizeInvoke is not only used in WinForm. For example, a Calculator class provides an add () method plus two numbers, which is implemented by IsynchronizeInvoke. The user must determine whether the ISYNCHRONIZEINVOKE.Invoke () method is performed in the correct thread (see list a).

Maybe you don't want to call synchronous calls because it is sent to another thread. You can implement it through the beginInvoke () and endInvoke () methods. You can use these methods in accordance with General .NET Non-Synchronous Mode: Use BeGinInvoke () to send calls, use endInvoke () to implement or use to prompt when completed and collect the return result.

It is also worth mentioning that isynchronizeInvoke method is not a safe type. The type does not match will result in an exception when executed, not compiling errors. So you should pay more attention when using IsynchronizeInvoke, because the editor cannot check the execution error.

Implementation IsynchronizeInvoke requires you to use a proxy to dynamically modify the method in later binding. Each agent type provides a DynamicInvoke () method:

Public Object DynamicInvoke (Object []

ARGS);

In theory, you must put a method agent in a real thread that needs to provide an object run, and causes the DynamicInvoke () method to call the INVOKE () and the agent in the BeginInvoke () method. ISYNCHRONIZEINVOKE is a non-general programming skill. The source file included in this article contains a Helper Class and a Test Program for the Synchronizer, which is used to demonstrate the Calculator class in the list A. How to use the Synchronizer class to implement IsynchronizeInvoke. Synchronizer is an ordinary implementation of IsynchronizeInvoke, you can use its derive class or use it as an object, and assign IsynchronizeInvoke implementation to it.

An important element used to implement SYNCHRONIZER is the use of a nested class called Workerthread (NESTED CLASS). There is a work item in Workerthread. The method proxy and parameters are included in the WorkItem class. Invoke () and beginInvoke () are used to join a work item instance to the query. Workerthread has created a new .NET WORKER thread that is responsible for monitoring the query task of work items. After querying the project, Worker reads them and then calls the DynamicInvoke () method. -J.l.

Problem: HTML Document and Clipboard (Clipboard) My program needs to put the HTML document into the clipboard, but I don't know how to deal with to make other programs can also be used. I have viewed some reference instructions on HTML Clipboard Format (cf_html), but I still can't find an accurate definition. How should I do? Solution: CF_HTML CLIPBOARD FORMAT with Windows Clipboard is really easy to make, part of it is because it is not a clipboard in Clipboard Format; it is a registered format, so it is not a constant because it The value will change due to the different systems. You can call - RegisterClipboardFormat through a simple API to get a value of a registered clipboard format. The first call of this function is performed by a given string, which returns a unique value between the range between C000-FFF. Each subsequent call (SUBSEQUENT CALL) returns the same value. The key string used in this format is "HTML FORMAT":

Private Declare Function_

RegisterClipboardFormat_

LIB "user32" _

Alias ​​"RegisterClipboardFormata" _

(Byval LPSTRING AS STRING) AS Long

DIM CF_HTML AS Long

Const Reghtml As String = "HTML FORMAT"

Cf_html = _

RegisterClipboardFormat (Reghtml)

You must first build a descriptive header and put it in the data before putting the HTML data into the clipboard. This header will provide other programs to describe the offset (Offset) of version information, HTML starting data, and information about the actual selection (Actual Selection). Part of the HTML document that the user may select is even just an element (such as a few lines in a table) as a selection area. Other parts of the page, such as inline style definition, may be required to be fully rendered. You don't just put the originally selected HTML area into the clipboard, but also need to put it into a header, it looks like this:

Version: 1.0

StartHtml: 000000258

Endhtml: 000001491

StartFragment: 000001172

Endfragment: 000001411

The application determines which data needs to be pasted through the startfragment and endfragment properties, which may be formatted with the remaining HTML with the remaining HTML. You must make an HTML annotation into the data in order to identify the selected part. Obviously, you must complete it before building the last header, otherwise the offset will change. An Opening / Closing Comment Tag for the selected data is "

"with"

"(See List 1).

Here I can not introduce this header's various aspects, so I can only explain some points, you can refer to sample code and make a more in-depth understanding (see resources). You must remember a few points. The offset in the header is based on zero-based, so you must use this to adjust your string operating program (String-manipulation routine). Moreover, if you don't just read more and need to write Header, you must understand the number of characters (such as Internet Explorer [IE] is 9, Word is 10). Finally, if you just put the cf_html into the clipboard, you can't handle programs such as Word and FrontPage. You must provide a clipboard to provide a formatted HTML's plain text compilation to achieve the results you want. Many tools for performing HTML-TO-TEXT conversion or Macho may need to perform their own parallel. But Windows programmers do not need to manually parse HTML. You can replace this daily task with OS:

Public Function HTML2Text (Byval Data _

As string) AS STRING

DIM OBJ AS Object

ON Error ResMe next

Set obj = _

CreateObject ("htmlfile")

Obj.open

Obj.write data

HTML2Text = Obj.Body.innertext

END FUNCTION

Upgrade IE is not the fastest way to resolve HTML, but it is a very good way. -K.e.p.

About the Author:

Juval Lowy is an experienced software architect and is the person in charge of Idesign. This is a consultation and training company specializing in .NET design and .net transplantation. As a regional head of Microsoft in Silicon Valley, JuVal is responsible for helping to use .NET to enter into the enterprise. JuVal has a book book, you can pass

Www.ideesign.net contact him.

Karl E. Peterson is a regional transport planning agent GIS analyst, as well as Visual Studio magazine technicians and editorial advisers, as well as MiCrosoft MVP and several vsm forum sectors. Want to see more VB code instances written by Karl, you can browse

Www.mvps.org/vb website.

转载请注明原文地址:https://www.9cbs.com/read-116820.html

New Post(0)