Communication between different processes

  Communication between processes in order to solve the problem of data transmission between the different processes, which would allow different programs interact with data. Process communication manner: 1, shear plate; 2, COM; 3, memory-mapped file; 4, WCF

1, clipboard Clipboard transfer objects between processes

  The clipboard is a public area for the application using. In .NET a DataFormats a given class that contains static fields, defines the data types can be stored in the clipboard. Clipboard class can be put to use data to the clipboard.

  As the text into the clipboard, to use SetDataObject: Clipboard.SetDataObject ( "clipboard Text 2"); at the time of reading, first determine whether or not there is text in the clipboard, then read:
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Text))
{
    label1.Text = data.GetData(DataFormats.Text).ToString();
}

  Placing the custom data to the clipboard, a custom image class, and marked as serializable (namespace used herein are: TestClipboard). Key custom data type object is placed to the clipboard DataObject class, which implements the IDataObject interface. It is like a container, will be placed on the storage data clipboard.

[The Serializable]
 public  class MyPic 
{ 
    ///  <Summary> 
    /// image
     ///  </ Summary> 
    public Image the Img;
     ///  <Summary> 
    /// image information
     ///  </ Summary> 
    public  String ImgInfo; 
} 
public  void SetMyPicToClipboard () 
{ 
    MyPic obj = new new MyPic (); 
    obj.Img = Properties.Resources.Image; 
    obj.ImgInfo = " test will be saved to the clipboard custom types " ;
     // create data objects, and data is loaded
    = Dataobj the IDataObject new new the DataObject (obj); 

    // Other types of data may be placed in the same object 
    / * 
    dataObj.SetData (DataFormats.UnicodeText, "Text Test"); 
    dataObj.SetData (DataFormats.Bitmap, Properties.Resources.Image ); 
     * / 
    // copied to the clipboard, the second parameter is not empty the program exits 
    Clipboard.SetDataObject (dataobj, to true ); 
}

  However, using the method Clipboard.SetDataObject after a DataObject objects into the clipboard, when access to the outside world, need to type the full name of the specified object. If a data type can only be accessed in the specified process, you can use that way, specify the namespace.

 // first determine whether there is data on the clipboard I: a fully qualified namespace type 
 IF (Clipboard.ContainsData ( " WindowsFormsApplication1.MyPic " )) 
 { 
     the IDataObject dataobj = Clipboard.GetDataObject (); // read data 
     MyPic myPic dataObj.GetData = ( " WindowsFormsApplication1.MyPic " ) AS MyPic; // convert data 
     pictureBox1.Image = myPic.Img; 
     textBox1.Text = myPic.ImgInfo; 
 }

2, the process of achieving synchronization using FileSystemWatcher

  The component can monitor specific folders or files, such as in this folder corresponding event triggered when a file is deleted or changed content. This component allows multiple processes to simultaneously monitor a file, this can act between "temporary" process communication channels.
  The key point is to achieve synchronization process: setting up shared files and read and write permissions correctly.
/// <summary>
/// 实现写入数据
/// </summary>
/// <param name="fileName"></param>
public void SetText(string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Read))
    {
        using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8))
        {
            writer.Write("内容");
        }
    }
}
/// <summary>
/// 实现读取数据
/// </summary>
/// <param name="fileName"></param>
public void ReadText(string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
        {
            string txt = reader.ReadToEnd();
        }
    }
}

  Then, change the use FileSystemWatcher component Changed event monitoring file has occurred. In network applications, this component may be used to monitor specific dedicated file uploaded files, when the user uploads the file was found, the system automatically initiates a series of processing flow.

3, using memory-mapped files (Memory Mapped File) implement interprocess communication

  Meaning: in memory to open up a dedicated storage area for data, this particular area of ​​the hard disk file, respectively. The process of mapping this memory area to its own address space, as complete as access common memory access it. windows in the system paging file and the hibernation file is so achievable. You need to reference the namespace System.IO.MemoryMappedFiles.

  MemoryMappedFile object represents a memory-mapped file, create a memory-mapped file through its CreateFromFile method according to existing disk file (note the use of the resources released immediately after, in fact it is the core of the object corresponding to the operating system). Wherein, when the capacity of the memory map is not specified, the default file size is equal. When the specified size, its value can not be smaller than the size of the existing file. If the specified disk file size is greater than the size of the disk file will automatically grow to the size of the capacity of memory-mapped file declarations.

  After creating MemoryMappedFile objects, you can not be directly read and write, you must use MemoryMappedViewAccessor objects (memory-mapped access view objects) operation. You can create objects using an access method MemoryMappedFile object. Wherein the specified range may require access to a file from the first few bytes to several bytes. When writing parameters, which also need to indicate what position would like to write. Also be used to read data in the Read method MemoryMappedViewAccessor.

 

MemoryMappedFile memoryFile = MemoryMappedFile.CreateFromFile("Text.Config", FileMode.OpenOrCreate, "Config", 1400);//kb;
MemoryMappedViewAccessor accessor = memoryFile.CreateViewAccessor(0, 1024);
accessor.Write(0, '2');

  In the same process, you can create multiple "access memory-mapped view object" for the same memory-mapped file, thus allowing simultaneous modify different parts of the same file, when you close these objects by the operating system will ensure that all changes are written back to the original file.

  MemoryMappedViewAccessor the Write and Read have generic methods, only a single type of structure type (application type in the program is running, the computer can not know how many bytes of data is written to the memory-mapped file, the type of object references located in the managed heap, calculate their size need to go through, but very time-consuming (and other objects that may be referenced objects), the efficiency of sound memory-mapped files).
  After serialization can be used, the reference object to serialize the data written in the memory-mapped files.
MemoryMappedFile memoryFile = MemoryMappedFile.CreateFromFile("Text.Config", FileMode.OpenOrCreate, "Config", 1400);//kb;
MemoryMappedViewStream stream = memoryFile.CreateViewStream();
MyPic obj = new MyPic();
stream.Seek(0, SeekOrigin.Begin);
new BinaryFormatter().Serialize(stream, obj);

4, implemented using WCF process communication via conduit

  "Pipe (Pipe)" Windows is an interprocess communication mechanism is provided for transmitting data between two processes with each other. Windows provides two types of pipes: anonymous pipes (Anonymous Pipe), named pipes (Named Pipe)

  1. Anonymous pipes: allow only one-way communication, because there is no name, so the two processes to communicate should be the parent-child relationship, the parent process when creating a child process is responsible for the transfer on behalf of an anonymous pipe handle to the child process, the child process through the Gets the parent process handle data transmission. The advantage is the small footprint, high efficiency; drawback is that the communication process must be a parent-child relationship, limiting usage scenarios.
  2. Named Pipes: This type of pipe in the machine has a unique name, can be used for single / two-way communication between a service process and multiple client processes. A named pipe is a message-based communication mode, i.e., a process once more messages to other processes may occur continuously (message divided by a delimiter between messages), extract the complete message recipient by delimiters.

  System.IO.Pipes in the namespace, provides some anonymous pipeline achieve the realization of the pipeline based inter-process communication, such as AnonymousPipeClientStream and AnonymousPipeServerStream can be used, but NamedPipeClientStream and NamedPipeServerStream can be achieved named pipes. But compared to the WCF, which is more complicated, WCF pipeline process communication easier and more flexible.

  WCF applications using named pipes to achieve interprocess communication: WCF provides a NetNamedPipeBinding binding, it can be achieved using named pipes in the formation process communication.

 

 

Guess you like

Origin www.cnblogs.com/pilgrim/p/11285218.html