2015-12-02 37 views
2

我有一個Outlook插件和一個桌面應用程序。我在兩個應用程序中都實現了相同的同步過程。但是,我不想讓用戶同時從兩個應用程序運行同步過程。因此,當同步正在運行並且用戶嘗試從另一個應用程序開始同步。他/她顯示一條消息,表示同步已經在運行,並且同步請求被中止。爲了實現這一點,我正在考慮創建一個文件,並且每當一個應用程序啓動同步時,它就會在該文件中創建一個條目。因此,如果用戶然後嘗試從第二個應用程序開始同步,然後首先檢查文件是否存在條目,如果條目存在,則請求中止。是否有其他方法可以執行此操作?如何將消息從一個桌面應用程序傳遞到在同一臺計算機上運行的另一個桌面應用程序?

+0

套接字?管? – Dmitriy

+2

那麼像[互斥](https://msdn.microsoft.com/en-us/library/system.threading.mutex(v = vs.110).aspx)? –

+1

認爲,它是這樣的重複:http://stackoverflow.com/questions/4123923/synchronizing-2-processes-using-interprocess-synchronizations-objects-mutex-or或 – Dmitriy

回答

2

如果您可以控制這兩個應用程序,那麼您可以使用命名管道來啓動它們之間的通信。 命名管道是Windows中進程間通信的最佳選擇,它與服務器客戶端體系結構協同工作,並且存在大約簡化整個過程的.net包裝器named pipe

從那裏的代碼。

服務器代碼

var server = new NamedPipeServer<SomeClass>("MyServerPipe"); 

server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn) 
    { 
     Console.WriteLine("Client {0} is now connected!", conn.Id); 
     conn.PushMessage(new SomeClass { Text: "Welcome!" }); 
    }; 

server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message) 
    { 
     Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text); 
    }; 

// Start up the server asynchronously and begin listening for connections. 
// This method will return immediately while the server runs in a separate background thread. 
server.Start(); 

和客戶端代碼

var client = new NamedPipeClient<SomeClass>("MyServerPipe"); 

client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message) 
    { 
     Console.WriteLine("Server says: {0}", message.Text); 
    }; 

// Start up the client asynchronously and connect to the specified server pipe. 
// This method will return immediately while the client runs in a separate background thread. 
client.Start(); 

希望這會幫助你。

+0

我會用WCF抽象出管道。 – Aron

+0

它不是wcf管...沒有配置...但只有點名像「MyServerPipe」 –

+0

是的,爲什麼只有有香蕉(管)時,你可以有大猩猩(wcf)和babana(管)..請注意諷刺:P –

2

你不想要IPC。 IPC將這個問題歸結爲兩個將軍問題,即使在IPC的情況下,您也會遇到競爭狀況。

更合理的是創建第三個進程,一個負責存儲和同步數據的服務。我將把這個服務稱爲數據庫。

然後,Outlook插件和桌面應用程序只能連接並從數據庫中抓取數據。

它們也可以在需要時請求同步,但知道數據庫服務在任何時候只能運行一次同步。

最後,有很多免費產品可以爲您提供此功能,而無需您明確寫入,例如,您可以使用CouchDB服務進行數據同步/存儲。

相關問題