In practical applications, we often need to share information among multiple processes and implement inter-process control transmission.
There are many ways to share a local data file or a database. But the problem also arises-constantly operating on the hard disk will cause great damage to the hard disk hardware. In addition, Because reading the hard disk requires a lot of time, it also compromises the operating efficiency of the software!
Therefore, the more advanced level is our shared memory! In the past, this seems convenient in C/C ++, but VB6 requires many API operations. For. NET, APIs can only be implemented through delegation.
Now, NET4 provides us with a powerful function-memory file ing. The memory ing can perfectly share information between multiple processes!
The following is a simple example:
Implementation Task: process A writes information to the memory, and process B reads the information, so that process B shares the information of process.
Process A code is as follows:
Public Class Form1
Dim MF As System. IO. MemoryMappedFiles. MemoryMappedFile 'memorymappedfile memory ing file object
Private Sub Form1_Load (ByVal sender As System. Object, ByVal e As System. EventArgs) Handles MyBase. Load
MF = MF. CreateNew ("SYSIO", 5000) 'creates a memory ing file in the master shared process, which is 5000 bytes in size.
End Sub
Private Sub timereffectick (ByVal sender As System. Object, ByVal e As System. EventArgs) Handles Timer1.Tick
Dim buf (4) As Byte
Dim s As Single
Dim MS As System. IO. MemoryMappedFiles. MemoryMappedViewStream 'view stream of memory ing File
MS = MF. CreateViewStream ()
S = Rnd ()
Buf = BitConverter. GetBytes (s)
Ms. Write (buf, 0, buf. Length) 'writes information to the memory ing File
End Sub
End Class
The process B code is as follows:
Public Class Form1
Dim MF As System. IO. MemoryMappedFiles. MemoryMappedFile
Private Sub Form1_Load (ByVal sender As System. Object, ByVal e As System. EventArgs) Handles MyBase. Load
MF = MF. OpenExisting ("SYSIO") 'opens a memory ing, that is, the memory ing file created in the master shared process.
End Sub
Private Sub timereffectick (ByVal sender As System. Object, ByVal e As System. EventArgs) Handles Timer1.Tick
Dim buf () As Byte = {0, 0, 0, 0}
Dim MS As System. IO. MemoryMappedFiles. MemoryMappedViewStream
MS = MF. CreateViewStream ()
Ms. Read (buf, 0, buf. Length) 'reads the specified content in the ing File
Me. TextBox1.Text = BitConverter. ToSingle (buf, 0)
End Sub
End Class
From SANTOOK's column