vb.net使用内存映射文件进行通信

时间:2017-05-09 16:49:48

标签: vb.net c#-to-vb.net

您好。我转换了这个c#代码:

我正在使用这个项目:https://code.msdn.microsoft.com/Inter-process-communication-e96e94e7

    private void frmMain_Load(object sender, EventArgs e)
    {
        communicator = new MemoryMappedFileCommunicator("MemoryMappedShare", 4096);

        // This process reads data that begins in the position 0 and writes starting from the position 2000.
        communicator.ReadPosition = 0;
        communicator.WritePosition = 2000;

        // Creates an handler for the event that is raised when data are available in the
        // MemoryMappedFile.
        communicator.DataReceived += new EventHandler<MemoryMappedDataReceivedEventArgs>(communicator_DataReceived);
        communicator.StartReader();
    }

    private void communicator_DataReceived(object sender, MemoryMappedDataReceivedEventArgs e)
    {
        var receivedMessage = System.Text.Encoding.UTF8.GetString(e.Data);
        lstMessages.Items.Add(receivedMessage);
        lstMessages.SelectedIndex = lstMessages.Items.Count - 1;

        // Sends a message as a response.
        communicator.Write("Message from Windows App: data received at " + DateTime.Now);            
    }

到这样的vb.net:

 Dim communicator As New MemoryMappedFileCommunicator("MemoryMappedShare", 4096)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    ' This process reads data that begins in the position 2000 and writes starting from the position 0. 
    communicator.ReadPosition = 2000
    communicator.WritePosition = 0

    ' Creates an handler for the event that is raised when data are available in the MemoryMappedFile. 

    AddHandler communicator.DataReceived, AddressOf New EventHandler(Of MemoryMappedDataReceivedEventArgs)(communicator_DataReceived)
    communicator.StartReader() 

End Sub 

Private Sub communicator_DataReceived(ByVal sender As Object, ByVal e As MemoryMappedDataReceivedEventArgs)
    Dim receivedMessage = System.Text.Encoding.UTF8.GetString(e.Data)
    lstMessages.Items.Add(receivedMessage)
    lstMessages.SelectedIndex = lstMessages.Items.Count - 1

    ' Sends a message as a response.
    communicator.Write("Message from Windows App: data received at " + DateTime.Now)
End Sub

转换后,我在vb.net代码中收到错误,如下所示: VB.NET ERROR

EDelegate 'System.EventHandler(Of MemoryMappedFileManager.MemoryMappedDataReceivedEventArgs)' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.

在这一行:

    AddHandler communicator.DataReceived, AddressOf New EventHandler(Of MemoryMappedDataReceivedEventArgs)(communicator_DataReceived) 

1 个答案:

答案 0 :(得分:0)

您不能同时使用AddressOfNew EventHandler,因为AddressOf也会创建委托。

推荐的解决方案是将其更改为:

AddHandler communicator.DataReceived, AddressOf communicator_DataReceived

以下效果一样好,但不太可读:

AddHandler communicator.DataReceived, New EventHandler(Of MemoryMappedDataReceivedEventArgs)(AddressOf communicator_DataReceived)