Communication between processes is to solve the problem of data transmission between different processes, so that different programs can interact with data. Methods to realize process communication: 1. Clipboard; 2. COM; 3. Memory mapped files; 4. WCF
1. Clipboard transfers objects between processes
The clipboard is a public area for use in the application. In .NET, a DataFormats class is defined. This class contains some static fields and defines the data types that can be stored in the clipboard. Use the Clipboard class to put data into the clipboard.
If you put the text into the clipboard, use the method SetDataObject: ("Clipboard Text 2"); When reading, first determine whether there is text in the clipboard, and then read:
IDataObject data = (); if (()) { = ().ToString(); }
Place the custom data on the clipboard, customize a picture class, and mark it as serializable (the namespace used here is: TestClipboard). The key to placing custom data type objects on the clipboard is the DataObject class, which implements the IDataObject interface. It is like a container that stores data that will be placed on the clipboard.
[Serializable] public class MyPic { /// <summary> /// picture /// </summary> public Image Img; /// <summary> /// Picture information /// </summary> public string ImgInfo; } public void SetMyPicToClipboard() { MyPic obj = new MyPic(); = ; = "Test saves custom types to clipboard"; //Create data object and load data into IDataObject dataObj = new DataObject(obj); //Other types can also be placed in the same data object /* (, "test text"); (, ); */ //Copy to clipboard, the second parameter means that the program is not clear when exiting (dataObj, true); }
However, after using the method to place a DataObject object on the clipboard, when accessing the outside world, you need to specify the full type name of the object. If a certain data type can only be accessed in a specified process, you can use this method to specify the namespace.
//First determine whether there is my data on the clipboard: the namespace type needs to be fully qualified if (("")) { IDataObject dataObj = ();//Read data MyPic myPic = ("") as MyPic;//Convert data = ; = ; }
2. Use FileSystemWatcher to achieve process synchronization
This component can monitor specific folders or files, such as when a file is deleted or the content is changed, the corresponding event is triggered. This component allows multiple processes to monitor a file simultaneously, thereby acting as a "temporary" inter-process communication channel.
The key point in realizing process synchronization is: correctly set file sharing and read and write permissions.
/// <summary> /// Implement writing data/// </summary> /// <param name="fileName"></param> public void SetText(string fileName) { using (FileStream fs = new FileStream(fileName, , , )) { using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8)) { ("content"); } } } /// <summary> /// Implement reading data/// </summary> /// <param name="fileName"></param> public void ReadText(string fileName) { using (FileStream fs = new FileStream(fileName, , , )) { using (StreamReader reader = new StreamReader(fs, Encoding.UTF8)) { string txt = (); } } }
Then, use the Change event of the FileSystemWatcher component to monitor whether the file has changed. In a web application, this component can be used to monitor specific folders dedicated to uploading files. When a user is found to upload files, the system can automatically start a series of processing processes.
3. Use Memory Mapped File to implement process communication
Meaning: Open a dedicated area for storing data in memory, which corresponds to specific files on the hard disk. The process maps this memory area to its own address space and completes accessing it like accessing normal memory. This is how the system paging files and hibernation files in Windows are implemented. The namespace needs to be referenced.
The MemoryMappedFile object represents a memory mapped file. It uses its CreateFromFile method to create a memory mapped file based on the existing disk files (note that the resource must be released immediately after use, but in fact it corresponds to the core object of the operating system). Among them, the memory map capacity is equal to the file size when not specified. When a specified size is used, its value cannot be less than the existing size of the file. If the specified size is greater than the disk file size, the disk file will automatically grow to the capacity declared by the memory mapped file.
After creating a MemoryMappedFile object, it cannot be read and written directly. It must be operated using the MemoryMappedViewAccessor object (memory mapped view access object). You can use the MemoryMappedFile object method to create an access object. Among them, you can specify the range of files that need to be accessed, from the byte to the byte. When writing parameters, you also need to specify where to write what to write. At the same time, you can also use the Read method of MemoryMappedViewAccessor to read data.
MemoryMappedFile memoryFile = ("", , "Config", 1400);//kb; MemoryMappedViewAccessor accessor = (0, 1024); (0, '2');
In the same process, multiple "memory mapped view access objects" can be created for the same memory mapped file, allowing different parts of the same file to be modified simultaneously. When these objects are closed, the operating system ensures that all modifications are written back to the original file.
MemoryMappedViewAccessor's Write and Read have generic methods. Single type can only be a structure type (the application type is running, and the computer cannot know how many bytes of data should be written to the memory mapped file. The object of the reference type is located in the managed heap, and its size needs to be calculated, but it is very time-consuming (and the object may refer to other objects), the efficiency of the sound memory mapped file).
You can use serialization method to serialize the referenced object data and write it to the memory mapped file.
MemoryMappedFile memoryFile = ("", , "Config", 1400);//kb; MemoryMappedViewStream stream = (); MyPic obj = new MyPic(); (0, ); new BinaryFormatter().Serialize(stream, obj);
4. Use WCF to realize process communication through pipelines
"Pipe" is an inter-process communication mechanism provided by Windows, which is used to transfer data to each other between two processes. Windows provides two types of pipelines: Anonymous Pipe and Named Pipe
- Anonymous pipeline: Only one-way communication is allowed. Since there is no name, the two processes to communicate should be a parent-child relationship. When the parent process creates a child process, it is responsible for transmitting the handle representing the anonymous pipeline to the child process. The child process can obtain the data transmitted by the parent process through this handle. Its advantage is that it occupies less resources and has high efficiency; its disadvantage is that the communication process must be a father-son relationship, which limits usage scenarios.
- Named Pipeline: This type of pipeline has a natively unique name and can be used for single/two-way communication between one service process and multiple client processes. A named pipe is a message-based communication mode, that is, one process can continuously generate multiple messages to another process at one time (the messages are divided by the delimiter of the message), and the receiver extracts the complete message through the delimiter.
In the namespace, some are provided for implementing pipeline-based interprocess communication, such as AnonymousPipeClientStream and AnonymousPipeServerStream can be used to implement anonymous pipelines, while NamedPipeClientStream and NamedPipeServerStream can be used to implement named pipelines. However, compared with WCF, it is more cumbersome, and WCF's pipeline process communication is simpler and more flexible.
WCF applications use named pipes to implement process communication: WCF provides a NetNamedPipeBinding binding, which can implement process communication using named pipes in the formation.
The above is the detailed content of how to achieve communication between different processes in C#. For more information about communication between c#, please pay attention to my other related articles!