2 .Net应用程序之间的最佳通信方式?

时间:2010-04-10 21:39:59

标签: vb.net ipc

如果我控制两个应用程序,那么在VB.Net中编写的2个exe之间进行通信的最佳方式是什么。例如,我想从一个应用程序中删除一个XML文件,然后用另一个应用程序将其选中,但我不希望对该文件进行轮询。我听说过命名管道,但我发现它很复杂。什么是最有效的方法?

5 个答案:

答案 0 :(得分:7)

最简单的方法可能是使用Windows Communication Foundation。这个article有用VB.NET编写的示例代码。

答案 1 :(得分:4)

您不必轮询该文件。使用FileSystemWatcher

答案 2 :(得分:3)

一种简单的方法是使用WCF。接收方应用程序可以托管一个简单的WCF服务,发送方可以将文件发送给它。

答案 3 :(得分:1)

.NET 4包括对memory-mapped files的支持。有了这些,您甚至可以避免使用文件系统。但是,如果进程没有在同一台机器上运行,则必须使用其他方法(如其他人所述,WCF将是一个很好的方法)。

答案 4 :(得分:0)

如果您可以编辑.exe的文件,这是最简单的方法:

在其中一个.exe中添加FileSystemWatcher对象,并将Filter设置为特定文件,例如“Commands.txt”

FileSystemWatcher1.Path = Application.StartupPath
FileSystemWatcher1.NotifyFilter=NotifyFilters.LastWrite
FileSystemWatcher1.Filter = "Commands.txt"
FileSystemWatcher1.EnableRaisingEvents = True

要标记/停止监视,请将路径和EnableRaisingEvents属性设置为True或False

这是文件更改时引发的事件:

Private Sub FileSystemWatcher1_Changed(sender As System.Object, e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
    'Open the file and read the content.
    'you can use your own commands
End Sub

这样,您只会在文件发生变化时获得一个事件,而不需要使用计时器或其他任何东西。


另一个.exe文件,只需要编写要发送的命令或消息: 此示例每次都写入当前日期时间覆盖文件。

Dim Timestamp() As Byte = System.Text.Encoding.Default.GetBytes(Now.ToString)
Dim Fs As System.IO.FileStream
Fs = New System.IO.FileStream("Commands.txt", FileMode.Create, FileAccess.Write)
Fs.Write(Timestamp, 0, Timestamp.Length - 1)
Fs.Close()

完成!

相关问题