a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 編程 > C# > 正文

一個進程間通訊同步的C#框架引薦

2019-10-29 21:41:11
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了一個進程間通訊同步的C#框架,代碼具有相當的穩定性和可維護性,隨著.NET的開源也會被注入更多活力,推薦!需要的朋友可以參考下

0.背景簡介

微軟在 .NET 框架中提供了多種實用的線程同步手段,其中包括 monitor 類及 reader-writer鎖。但跨進程的同步方法還是非常欠缺。另外,目前也沒有方便的線程間及進程間傳遞消息的方法。例如C/S和SOA,又或者生產者/消費者模式中就常常需要傳遞消息。為此我編寫了一個獨立完整的框架,實現了跨線程和跨進程的同步和通訊。這框架內包含了信號量,信箱,內存映射文件,阻塞通道,及簡單消息流控制器等組件。這篇文章里提到的類同屬于一個開源的庫項目(BSD許可),你可以從這里下載到 www.cdrnet.net/projects/threadmsg/.

這個框架的目的是:

封裝性:通過MSMQ消息隊列發送消息的線程無需關心消息是發送到另一個線程還是另一臺機器。

簡單性:向其他進程發送消息只需調用一個方法。

注意:我刪除了本文中全部代碼的XML注釋以節省空間。如果你想知道這些方法和參數的詳細信息,請參考附件中的代碼。

1.先看一個簡單例子

使用了這個庫后,跨進程的消息傳遞將變得非常簡單。我將用一個小例子來作示范:一個控制臺程序,根據參數可以作為發送方也可以作為接收方運行。在發送程序里,你可以輸入一定的文本并發送到信箱內(返回key),接收程序將顯示所有從信箱內收到的消息。你可以運行無數個發送程序和接收程序,但是每個消息只會被具體的某一個接收程序所收到。

 

 
  1. [Serializable] 
  2. struct Message 
  3. public string Text; 
  4.  
  5. class Test 
  6. IMailBox mail; 
  7.  
  8. public Test() 
  9. mail = new ProcessMailBox("TMProcessTest",1024); 
  10.  
  11. public void RunWriter() 
  12. Console.WriteLine("Writer started"); 
  13. Message msg; 
  14. while(true
  15. msg.Text = Console.ReadLine(); 
  16. if(msg.Text.Equals("exit")) 
  17. break
  18. mail.Content = msg; 
  19.  
  20. public void RunReader() 
  21. Console.WriteLine("Reader started"); 
  22. while(true
  23. Message msg = (Message)mail.Content; 
  24. Console.WriteLine(msg.Text); 
  25.  
  26. [STAThread] 
  27. static void Main(string[] args) 
  28. Test test = new Test(); 
  29. if(args.Length > 0) 
  30. test.RunWriter(); 
  31. else 
  32. test.RunReader(); 

信箱一旦創建之后(這上面代碼里是 ProcessMailBox ),接收消息只需要讀取 Content 屬性,發送消息只需要給這個屬性賦值。當沒有數據時,獲取消息將會阻塞當前線程;發送消息時如果信箱里已經有數據,則會阻塞當前線程。正是有了這個阻塞,整個程序是完全基于中斷的,并且不會過度占用CPU(不需要進行輪詢)。發送和接收的消息可以是任意支持序列化(Serializable)的類型。

然而,實際上暗地里發生的事情有點復雜:消息通過內存映射文件來傳遞,這是目前唯一的跨進程共享內存的方法,這個例子里我們只會在 pagefile 里面產生虛擬文件。對這個虛擬文件的訪問是通過 win32 信號量來確保同步的。消息首先序列化成二進制,然后再寫進該文件,這就是為什么需要聲明Serializable屬性。內存映射文件和 win32 信號量都需要調用 NT內核的方法。多得了 .NET 框架中的 Marshal 類,我們可以避免編寫不安全的代碼。我們將在下面討論更多的細節。

2. .NET里面的跨線程/進程同步

線程/進程間的通訊需要共享內存或者其他內建機制來發送/接收數據。即使是采用共享內存的方式,也還需要一組同步方法來允許并發訪問。

同一個進程內的所有線程都共享公共的邏輯地址空間(堆)。對于不同進程,從 win2000 開始就已經無法共享內存。然而,不同的進程可以讀寫同一個文件。WinAPI提供了多種系統調用方法來映射文件到進程的邏輯空間,及訪問系統內核對象(會話)指向的 pagefile 里面的虛擬文件。無論是共享堆,還是共享文件,并發訪問都有可能導致數據不一致。我們就這個問題簡單討論一下,該怎樣確保線程/進程調用的有序性及數據的一致性。

2.1 線程同步

.NET 框架和 C# 提供了方便直觀的線程同步方法,即 monitor 類和 lock 語句(本文將不會討論 .NET 框架的互斥量)。對于線程同步,雖然本文提供了其他方法,我們還是推薦使用 lock 語句。

 

 
  1. void Work1() 
  2. NonCriticalSection1(); 
  3. Monitor.Enter(this); 
  4. try 
  5. CriticalSection(); 
  6. finally 
  7. Monitor.Exit(this); 
  8. NonCriticalSection2(); 
  9.  
  10. void Work2() 
  11. NonCriticalSection1(); 
  12. lock(this
  13. CriticalSection(); 
  14. NonCriticalSection2(); 

Work1 和 Work2 是等價的。在C#里面,很多人喜歡第二個方法,因為它更短,且不容易出錯。

2.2 跨線程信號量

信號量是經典的同步基本概念之一(由 Edsger Dijkstra 引入)。信號量是指一個有計數器及兩個操作的對象。它的兩個操作是:獲取(也叫P或者等待),釋放(也叫V或者收到信號)。信號量在獲取操作時如果計數器為0則阻塞,否則將計數器減一;在釋放時將計數器加一,且不會阻塞。雖然信號量的原理很簡單,但是實現起來有點麻煩。好在,內建的 monitor 類有阻塞特性,可以用來實現信號量。

 

 
  1. public sealed class ThreadSemaphore : ISemaphore 
  2. private int counter; 
  3. private readonly int max; 
  4.  
  5. public ThreadSemaphore() : this(0, int.Max) {} 
  6. public ThreadSemaphore(int initial) : this(initial, int.Max) {} 
  7. public ThreadSemaphore(int initial, int max) 
  8. this.counter = Math.Min(initial,max); 
  9. this.max = max; 
  10.  
  11. public void Acquire() 
  12. lock(this
  13. counter--; 
  14. if(counter < 0 && !Monitor.Wait(this)) 
  15. throw new SemaphoreFailedException(); 
  16.  
  17. public void Acquire(TimeSpan timeout) 
  18. lock(this
  19. counter--; 
  20. if(counter < 0 && !Monitor.Wait(this,timeout)) 
  21. throw new SemaphoreFailedException(); 
  22.  
  23. public void Release() 
  24. lock(this
  25. if(counter >= max) 
  26. throw new SemaphoreFailedException(); 
  27. if(counter < 0) 
  28. Monitor.Pulse(this); 
  29. counter++; 

信號量在復雜的阻塞情景下更加有用,例如我們后面將要討論的通道(channel)。你也可以使用信號量來實現臨界區的排他性(如下面的 Work3),但是我還是推薦使用內建的 lock 語句,像上面的 Work2 那樣。

請注意:如果使用不當,信號量也是有潛在危險的。正確的做法是:當獲取信號量失敗時,千萬不要再調用釋放操作;當獲取成功時,無論發生了什么錯誤,都要記得釋放信號量。遵循這樣的原則,你的同步才是正確的。Work3 中的 finally 語句就是為了保證正確釋放信號量。注意:獲取信號量( s.Acquire() )的操作必須放到 try 語句的外面,只有這樣,當獲取失敗時才不會調用釋放操作。

 

 
  1. ThreadSemaphore s = new ThreadSemaphore(1); 
  2. void Work3() 
  3. NonCriticalSection1(); 
  4. s.Acquire(); 
  5. try 
  6. CriticalSection(); 
  7. finally 
  8. s.Release(); 
  9. NonCriticalSection2(); 

2.3 跨進程信號量

為了協調不同進程訪問同一資源,我們需要用到上面討論過的概念。很不幸,.NET 中的 monitor 類不可以跨進程使用。但是,win32 API提供的內核信號量對象可以用來實現跨進程同步。 Robin Galloway-Lunn 介紹了怎樣將 win32 的信號量映射到 .NET 中(見 Using Win32 Semaphores in C# )。我們的實現也類似:

 

 
  1. [DllImport("kernel32",EntryPoint="CreateSemaphore"
  2. SetLastError=true,CharSet=CharSet.Unicode)] 
  3. internal static extern uint CreateSemaphore( 
  4. SecurityAttributes auth, int initialCount, 
  5. int maximumCount, string name); 
  6.  
  7. [DllImport("kernel32",EntryPoint="WaitForSingleObject"
  8. SetLastError=true,CharSet=CharSet.Unicode)] 
  9. internal static extern uint WaitForSingleObject( 
  10. uint hHandle, uint dwMilliseconds); 
  11.  
  12. [DllImport("kernel32",EntryPoint="ReleaseSemaphore"
  13. SetLastError=true,CharSet=CharSet.Unicode)] 
  14. [return : MarshalAs( UnmanagedType.VariantBool )] 
  15. internal static extern bool ReleaseSemaphore( 
  16. uint hHandle, int lReleaseCount, out int lpPreviousCount); 
  17.  
  18. [DllImport("kernel32",EntryPoint="CloseHandle",SetLastError=true
  19. CharSet=CharSet.Unicode)] 
  20. [return : MarshalAs( UnmanagedType.VariantBool )] 
  21. internal static extern bool CloseHandle(uint hHandle); 
  22.  
  23. public class ProcessSemaphore : ISemaphore, IDisposable 
  24. private uint handle; 
  25. private readonly uint interruptReactionTime; 
  26.  
  27. public ProcessSemaphore(string name) : this
  28. name,0,int.MaxValue,500) {} 
  29. public ProcessSemaphore(string name, int initial) : this
  30. name,initial,int.MaxValue,500) {} 
  31. public ProcessSemaphore(string name, int initial, 
  32. int max, int interruptReactionTime) 
  33. {  
  34. this.interruptReactionTime = (uint)interruptReactionTime; 
  35. this.handle = NTKernel.CreateSemaphore(null, initial, max, name); 
  36. if(handle == 0) 
  37. throw new SemaphoreFailedException(); 
  38.  
  39. public void Acquire() 
  40. while(true
  41. //looped 0.5s timeout to make NT-blocked threads interruptable. 
  42. uint res = NTKernel.WaitForSingleObject(handle, 
  43. interruptReactionTime); 
  44. try {System.Threading.Thread.Sleep(0);} 
  45. catch(System.Threading.ThreadInterruptedException e) 
  46. if(res == 0) 
  47. //Rollback 
  48. int previousCount; 
  49. NTKernel.ReleaseSemaphore(handle,1,out previousCount); 
  50. throw e; 
  51. if(res == 0) 
  52. return
  53. if(res != 258) 
  54. throw new SemaphoreFailedException(); 
  55.  
  56. public void Acquire(TimeSpan timeout) 
  57. uint milliseconds = (uint)timeout.TotalMilliseconds; 
  58. if(NTKernel.WaitForSingleObject(handle, milliseconds) != 0) 
  59. throw new SemaphoreFailedException();  
  60.  
  61. public void Release() 
  62. int previousCount; 
  63. if(!NTKernel.ReleaseSemaphore(handle, 1, out previousCount)) 
  64. throw new SemaphoreFailedException();  
  65.  
  66. #region IDisposable Member 
  67. public void Dispose() 
  68. if(handle != 0) 
  69. if(NTKernel.CloseHandle(handle)) 
  70. handle = 0; 
  71. #endregion 

有一點很重要:win32中的信號量是可以命名的。這允許其他進程通過名字來創建相應信號量的句柄。為了讓阻塞線程可以中斷,我們使用了一個(不好)的替代方法:使用超時和 Sleep(0)。我們需要中斷來安全關閉線程。更好的做法是:確定沒有線程阻塞之后才釋放信號量,這樣程序才可以完全釋放資源并正確退出。

你可能也注意到了:跨線程和跨進程的信號量都使用了相同的接口。所有相關的類都使用了這種模式,以實現上面背景介紹中提到的封閉性。需要注意:出于性能考慮,你不應該將跨進程的信號量用到跨線程的場景,也不應該將跨線程的實現用到單線程的場景。

3. 跨進程共享內存:內存映射文件

我們已經實現了跨線程和跨進程的共享資源訪問同步。但是傳遞/接收消息還需要共享資源。對于線程來說,只需要聲明一個類成員變量就可以了。但是對于跨進程來說,我們需要使用到 win32 API 提供的內存映射文件(Memory Mapped Files,簡稱MMF)。使用 MMF和使用 win32 信號量差不多。我們需要先調用 CreateFileMapping 方法來創建一個內存映射文件的句柄:

 

 
  1. [DllImport("Kernel32.dll",EntryPoint="CreateFileMapping"
  2. SetLastError=true,CharSet=CharSet.Unicode)] 
  3. internal static extern IntPtr CreateFileMapping(uint hFile, 
  4. SecurityAttributes lpAttributes, uint flProtect, 
  5. uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName); 
  6.  
  7. [DllImport("Kernel32.dll",EntryPoint="MapViewOfFile"
  8. SetLastError=true,CharSet=CharSet.Unicode)] 
  9. internal static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, 
  10. uint dwDesiredAccess, uint dwFileOffsetHigh, 
  11. uint dwFileOffsetLow, uint dwNumberOfBytesToMap); 
  12.  
  13. [DllImport("Kernel32.dll",EntryPoint="UnmapViewOfFile"
  14. SetLastError=true,CharSet=CharSet.Unicode)] 
  15. [return : MarshalAs( UnmanagedType.VariantBool )] 
  16. internal static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); 
  17.  
  18. public static MemoryMappedFile CreateFile(string name, 
  19. FileAccess access, int size) 
  20. if(size < 0) 
  21. throw new ArgumentException("Size must not be negative","size"); 
  22.  
  23. IntPtr fileMapping = NTKernel.CreateFileMapping(0xFFFFFFFFu,null
  24. (uint)access,0,(uint)size,name); 
  25. if(fileMapping == IntPtr.Zero) 
  26. throw new MemoryMappingFailedException(); 
  27.  
  28. return new MemoryMappedFile(fileMapping,size,access); 

我們希望直接使用 pagefile 中的虛擬文件,所以我們用 -1(0xFFFFFFFF) 來作為文件句柄來創建我們的內存映射文件句柄。我們也指定了必填的文件大小,以及相應的名稱。這樣其他進程就可以通過這個名稱來同時訪問該映射文件。創建了內存映射文件后,我們就可以映射這個文件不同的部分(通過偏移量和字節大小來指定)到我們的進程地址空間。我們通過 MapViewOfFile 系統方法來指定:

 

 
  1. public MemoryMappedFileView CreateView(int offset, int size, 
  2. MemoryMappedFileView.ViewAccess access) 
  3. if(this.access == FileAccess.ReadOnly && access == 
  4. MemoryMappedFileView.ViewAccess.ReadWrite) 
  5. throw new ArgumentException( 
  6. "Only read access to views allowed on files without write access"
  7. "access"); 
  8. if(offset < 0) 
  9. throw new ArgumentException("Offset must not be negative","size"); 
  10. if(size < 0) 
  11. throw new ArgumentException("Size must not be negative","size"); 
  12. IntPtr mappedView = NTKernel.MapViewOfFile(fileMapping, 
  13. (uint)access,0,(uint)offset,(uint)size); 
  14. return new MemoryMappedFileView(mappedView,size,access); 

在不安全的代碼中,我們可以將返回的指針強制轉換成我們指定的類型。盡管如此,我們不希望有不安全的代碼存在,所以我們使用 Marshal 類來從中讀寫我們的數據。偏移量參數是用來從哪里開始讀寫數據,相對于指定的映射視圖的地址。

 

 
  1. public byte ReadByte(int offset) 
  2. return Marshal.ReadByte(mappedView,offset); 
  3. public void WriteByte(byte data, int offset) 
  4. Marshal.WriteByte(mappedView,offset,data); 
  5.  
  6. public int ReadInt32(int offset) 
  7. return Marshal.ReadInt32(mappedView,offset); 
  8. public void WriteInt32(int data, int offset) 
  9. Marshal.WriteInt32(mappedView,offset,data); 
  10.  
  11. public void ReadBytes(byte[] data, int offset) 
  12. for(int i=0;i<data.Length;i++) 
  13. data[i] = Marshal.ReadByte(mappedView,offset+i); 
  14. public void WriteBytes(byte[] data, int offset) 
  15. for(int i=0;i<data.Length;i++) 
  16. Marshal.WriteByte(mappedView,offset+i,data[i]); 

但是,我們希望讀寫整個對象樹到文件中,所以我們需要支持自動進行序列化和反序列化的方法。

 

 
  1. public object ReadDeserialize(int offset, int length) 
  2. byte[] binaryData = new byte[length]; 
  3. ReadBytes(binaryData,offset); 
  4. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter 
  5. new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
  6. System.IO.MemoryStream ms = new System.IO.MemoryStream( 
  7. binaryData,0,length,true,true); 
  8. object data = formatter.Deserialize(ms); 
  9. ms.Close(); 
  10. return data; 
  11. public void WriteSerialize(object data, int offset, int length) 
  12. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter 
  13. new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
  14. byte[] binaryData = new byte[length]; 
  15. System.IO.MemoryStream ms = new System.IO.MemoryStream( 
  16. binaryData,0,length,true,true); 
  17. formatter.Serialize(ms,data); 
  18. ms.Flush(); 
  19. ms.Close(); 
  20. WriteBytes(binaryData,offset); 

請注意:對象序列化之后的大小不應該超過映射視圖的大小。序列化之后的大小總是比對象本身占用的內存要大的。我沒有試過直接將對象內存流綁定到映射視圖,那樣做應該也可以,甚至可能帶來少量的性能提升。

4. 信箱:在線程/進程間傳遞消息

這里的信箱與 Email 及 NT 中的郵件槽(Mailslots)無關。它是一個只能保留一個對象的安全共享內存結構。信箱的內容通過一個屬性來讀寫。如果信箱內容為空,試圖讀取該信箱的線程將會阻塞,直到另一個線程往其中寫內容。如果信箱已經有了內容,當一個線程試圖往其中寫內容時將被阻塞,直到另一個線程將信箱內容讀取出去。信箱的內容只能被讀取一次,它的引用在讀取后自動被刪除。基于上面的代碼,我們已經可以實現信箱了。

4.1 跨線程的信箱

我們可以使用兩個信號量來實現一個信箱:一個信號量在信箱內容為空時觸發,另一個在信箱有內容時觸發。在讀取內容之前,線程先等待信箱已經填充了內容,讀取之后觸發空信號量。在寫入內容之前,線程先等待信箱內容清空,寫入之后觸發滿信號量。注意:空信號量在一開始時就被觸發了。

 

 
  1. public sealed class ThreadMailBox : IMailBox 
  2. private object content; 
  3. private ThreadSemaphore empty, full; 
  4.  
  5. public ThreadMailBox() 
  6. empty = new ThreadSemaphore(1,1); 
  7. full = new ThreadSemaphore(0,1); 
  8.  
  9. public object Content 
  10. get 
  11. full.Acquire(); 
  12. object item = content; 
  13. empty.Release(); 
  14. return item; 
  15. set 
  16. empty.Acquire(); 
  17. content = value; 
  18. full.Release(); 

4.2 跨進程信箱

跨進程信箱與跨線程信箱的實現基本上一樣簡單。不同的是我們使用兩個跨進程的信號量,并且我們使用內存映射文件來代替類成員變量。由于序列化可能會失敗,我們使用了一小段異常處理來回滾信箱的狀態。失敗的原因有很多(無效句柄,拒絕訪問,文件大小問題,Serializable屬性缺失等等)。

 

 
  1. public sealed class ProcessMailBox : IMailBox, IDisposable 
  2. private MemoryMappedFile file; 
  3. private MemoryMappedFileView view; 
  4. private ProcessSemaphore empty, full; 
  5.  
  6. public ProcessMailBox(string name,int size) 
  7. empty = new ProcessSemaphore(name+".EmptySemaphore.MailBox",1,1); 
  8. full = new ProcessSemaphore(name+".FullSemaphore.MailBox",0,1); 
  9. file = MemoryMappedFile.CreateFile(name+".MemoryMappedFile.MailBox"
  10. MemoryMappedFile.FileAccess.ReadWrite,size); 
  11. view = file.CreateView(0,size, 
  12. MemoryMappedFileView.ViewAccess.ReadWrite); 
  13.  
  14. public object Content 
  15. get 
  16. full.Acquire(); 
  17. object item; 
  18. try {item = view.ReadDeserialize();} 
  19. catch(Exception e) 
  20. //Rollback 
  21. full.Release(); 
  22. throw e; 
  23. empty.Release(); 
  24. return item; 
  25.  
  26. set 
  27. empty.Acquire(); 
  28. try {view.WriteSerialize(value);} 
  29. catch(Exception e) 
  30. //Rollback 
  31. empty.Release(); 
  32. throw e; 
  33. full.Release(); 
  34.  
  35. #region IDisposable Member 
  36. public void Dispose() 
  37. view.Dispose(); 
  38. file.Dispose(); 
  39. empty.Dispose(); 
  40. full.Dispose(); 
  41. #endregion 

到這里我們已經實現了跨進程消息傳遞(IPC)所需要的組件。你可能需要再回頭本文開頭的那個例子,看看 ProcessMailBox 應該如何使用。

5.通道:基于隊列的消息傳遞

信箱最大的限制是它們每次只能保存一個對象。如果一系列線程(使用同一個信箱)中的一個線程需要比較長的時間來處理特定的命令,那么整個系列都會阻塞。通常我們會使用緩沖的消息通道來處理,這樣你可以在方便的時候從中讀取消息,而不會阻塞消息發送者。這種緩沖通過通道來實現,這里的通道比信箱要復雜一些。同樣,我們將分別從線程和進程級別來討論通道的實現。

5.1 可靠性

信箱和通道的另一個重要的不同是:通道擁有可靠性。例如:自動將發送失敗(可能由于線程等待鎖的過程中被中斷)的消息轉存到一個內置的容器中。這意味著處理通道的線程可以安全地停止,同時不會丟失隊列中的消息。這通過兩個抽象類來實現, ThreadReliability 和 ProcessReliability。每個通道的實現類都繼承其中的一個類。

5.2 跨線程的通道

跨線程的通道基于信箱來實現,但是使用一個同步的隊列來作為消息緩沖而不是一個變量。得益于信號量,通道在空隊列時阻塞接收線程,在隊列滿時阻塞發送線程。這樣你就不會碰到由入隊/出隊引發的錯誤。為了實現這個效果,我們用隊列大小來初始化空信號量,用0來初始化滿信號量。如果某個發送線程在等待入隊的時候被中斷,我們將消息復制到內置容器中,并將異常往外面拋。在接收操作中,我們不需要做異常處理,因為即使線程被中斷你也不會丟失任何消息。注意:線程只有在阻塞狀態才能被中斷,就像調用信號量的獲取操作(Aquire)方法時。

 

 
  1. public sealed class ThreadChannel : ThreadReliability, IChannel 
  2. private Queue queue; 
  3. private ThreadSemaphore empty, full; 
  4.  
  5. public ThreadChannel(int size) 
  6. queue = Queue.Synchronized(new Queue(size)); 
  7. empty = new ThreadSemaphore(size,size); 
  8. full = new ThreadSemaphore(0,size); 
  9.  
  10. public void Send(object item) 
  11. try {empty.Acquire();} 
  12. catch(System.Threading.ThreadInterruptedException e) 
  13. DumpItem(item); 
  14. throw e; 
  15. queue.Enqueue(item); 
  16. full.Release(); 
  17.  
  18. public void Send(object item, TimeSpan timeout) 
  19. try {empty.Acquire(timeout);} 
  20. ... 
  21.  
  22. public object Receive() 
  23. full.Acquire(); 
  24. object item = queue.Dequeue(); 
  25. empty.Release(); 
  26. return item; 
  27.  
  28. public object Receive(TimeSpan timeout) 
  29. full.Acquire(timeout); 
  30. ... 
  31.  
  32. protected override void DumpStructure() 
  33. lock(queue.SyncRoot) 
  34. foreach(object item in queue) 
  35. DumpItem(item); 
  36. queue.Clear(); 

5.3 跨進程通道

實現跨進程通道有點麻煩,因為你需要首先提供一個跨進程的緩沖區。一個可能的解決方法是使用跨進程信箱并根據需要將接收/發送方法加入隊列。為了避免這種方案的幾個缺點,我們將直接使用內存映射文件來實現一個隊列。MemoryMappedArray 類將內存映射文件分成幾部分,可以直接使用數組索引來訪問。 MemoryMappedQueue 類,為這個數組提供了一個經典的環(更多細節請查看附件中的代碼)。為了支持直接以 byte/integer 類型訪問數據并同時支持二進制序列化,調用方需要先調用入隊(Enqueue)/出隊(Dequeue)操作,然后根據需要使用讀寫方法(隊列會自動將數據放到正確的位置)。這兩個類都不是線程和進程安全的,所以我們需要使用跨進程的信號量來模擬互斥量(也可以使用 win32 互斥量),以此實現相互間的互斥訪問。除了這兩個類,跨進程的通道基本上和跨線程信箱一樣。同樣,我們也需要在 Send() 中處理線程中斷及序列化可能失敗的問題。

 

 
  1. public sealed class ProcessChannel : ProcessReliability, IChannel, IDisposable 
  2. private MemoryMappedFile file; 
  3. private MemoryMappedFileView view; 
  4. private MemoryMappedQueue queue; 
  5. private ProcessSemaphore empty, full, mutex; 
  6.  
  7. public ProcessChannel( int size, string name, int maxBytesPerEntry) 
  8. int fileSize = 64+size*maxBytesPerEntry; 
  9.  
  10. empty = new ProcessSemaphore(name+".EmptySemaphore.Channel",size,size); 
  11. full = new ProcessSemaphore(name+".FullSemaphore.Channel",0,size); 
  12. mutex = new ProcessSemaphore(name+".MutexSemaphore.Channel",1,1); 
  13. file = MemoryMappedFile.CreateFile(name+".MemoryMappedFile.Channel"
  14. MemoryMappedFile.FileAccess.ReadWrite,fileSize); 
  15. view = file.CreateView(0,fileSize, 
  16. MemoryMappedFileView.ViewAccess.ReadWrite); 
  17. queue = new MemoryMappedQueue(view,size,maxBytesPerEntry,true,0); 
  18. if(queue.Length < size || queue.BytesPerEntry < maxBytesPerEntry) 
  19. throw new MemoryMappedArrayFailedException(); 
  20.  
  21. public void Send(object item) 
  22. try {empty.Acquire();} 
  23. catch(System.Threading.ThreadInterruptedException e) 
  24. DumpItemSynchronized(item); 
  25. throw e; 
  26. try {mutex.Acquire();} 
  27. catch(System.Threading.ThreadInterruptedException e) 
  28. DumpItemSynchronized(item); 
  29. empty.Release(); 
  30. throw e; 
  31. queue.Enqueue(); 
  32. try {queue.WriteSerialize(item,0);} 
  33. catch(Exception e) 
  34. queue.RollbackEnqueue(); 
  35. mutex.Release(); 
  36. empty.Release(); 
  37. throw e; 
  38. mutex.Release(); 
  39. full.Release(); 
  40.  
  41. public void Send(object item, TimeSpan timeout) 
  42. try {empty.Acquire(timeout);} 
  43. ... 
  44.  
  45. public object Receive() 
  46. full.Acquire(); 
  47. mutex.Acquire(); 
  48. object item; 
  49. queue.Dequeue(); 
  50. try {item = queue.ReadDeserialize(0);} 
  51. catch(Exception e) 
  52. queue.RollbackDequeue(); 
  53. mutex.Release(); 
  54. full.Release(); 
  55. throw e; 
  56. mutex.Release(); 
  57. empty.Release(); 
  58. return item; 
  59.  
  60. public object Receive(TimeSpan timeout) 
  61. full.Acquire(timeout); 
  62. ... 
  63.  
  64. protected override void DumpStructure() 
  65. mutex.Acquire(); 
  66. byte[][] dmp = queue.DumpClearAll(); 
  67. for(int i=0;i<dmp.Length;i++) 
  68. DumpItemSynchronized(dmp[i]); 
  69. mutex.Release(); 
  70.  
  71. #region IDisposable Member 
  72. public void Dispose() 
  73. view.Dispose(); 
  74. file.Dispose(); 
  75. empty.Dispose(); 
  76. full.Dispose(); 
  77. mutex.Dispose(); 
  78. #endregion 

6. 消息路由

我們目前已經實現了線程和進程同步及消息傳遞機制(使用信箱和通道)。當你使用阻塞隊列的時候,有可能會遇到這樣的問題:你需要在一個線程中同時監聽多個隊列。為了解決這樣的問題,我們提供了一些小型的類:通道轉發器,多用復用器,多路復用解碼器和通道事件網關。你也可以通過簡單的 IRunnable 模式來實現類似的通道處理器。IRunnable模式由兩個抽象類SingleRunnable和 MultiRunnable 來提供(具體細節請參考附件中的代碼)。

6.1 通道轉發器

通道轉發器僅僅監聽一個通道,然后將收到的消息轉發到另一個通道。如果有必要,轉發器可以將每個收到的消息放到一個信封中,并加上一個數字標記,然后再轉發出去(下面的多路利用器使用了這個特性)。

 

 
  1. public class ChannelForwarder : SingleRunnable 
  2. private IChannel source, target; 
  3. private readonly int envelope; 
  4.  
  5. public ChannelForwarder(IChannel source, 
  6. IChannel target, bool autoStart, bool waitOnStop) 
  7. : base(true,autoStart,waitOnStop) 
  8. this.source = source; 
  9. this.target = target; 
  10. this.envelope = -1; 
  11. public ChannelForwarder(IChannel source, IChannel target, 
  12. int envelope, bool autoStart, bool waitOnStop) 
  13. : base(true,autoStart,waitOnStop) 
  14. this.source = source; 
  15. this.target = target; 
  16. this.envelope = envelope; 
  17.  
  18. protected override void Run() 
  19. //NOTE: IChannel.Send is interrupt save and 
  20. //automatically dumps the argument. 
  21. if(envelope == -1) 
  22. while(running) 
  23. target.Send(source.Receive()); 
  24. else 
  25. MessageEnvelope env; 
  26. env.ID = envelope; 
  27. while(running) 
  28. env.Message = source.Receive(); 
  29. target.Send(env); 

6.2 通道多路復用器和通道復用解碼器

通道多路復用器監聽多個來源的通道并將接收到的消息(消息使用信封來標記來源消息)轉發到一個公共的輸出通道。這樣就可以一次性地監聽多個通道。復用解碼器則是監聽一個公共的輸出通道,然后根據信封將消息轉發到某個指定的輸出通道。

 

 
  1. public class ChannelMultiplexer : MultiRunnable 
  2. private ChannelForwarder[] forwarders; 
  3.  
  4. public ChannelMultiplexer(IChannel[] channels, int[] ids, 
  5. IChannel output, bool autoStart, bool waitOnStop) 
  6. int count = channels.Length; 
  7. if(count != ids.Length) 
  8. throw new ArgumentException("Channel and ID count mismatch.","ids"); 
  9.  
  10. forwarders = new ChannelForwarder[count]; 
  11. for(int i=0;i<count;i++) 
  12. forwarders[i] = new ChannelForwarder(channels[i], 
  13. output,ids[i],autoStart,waitOnStop); 
  14.  
  15. SetRunnables((SingleRunnable[])forwarders); 
  16.  
  17. public class ChannelDemultiplexer : SingleRunnable 
  18. private HybridDictionary dictionary; 
  19. private IChannel input; 
  20.  
  21. public ChannelDemultiplexer(IChannel[] channels, int[] ids, 
  22. IChannel input, bool autoStart, bool waitOnStop) 
  23. : base(true,autoStart,waitOnStop) 
  24. this.input = input; 
  25.  
  26. int count = channels.Length; 
  27. if(count != ids.Length) 
  28. throw new ArgumentException("Channel and ID count mismatch.","ids"); 
  29.  
  30. dictionary = new HybridDictionary(count,true); 
  31. for(int i=0;i<count;i++) 
  32. dictionary.add(ids[i],channels[i]); 
  33.  
  34. protected override void Run() 
  35. //NOTE: IChannel.Send is interrupt save and 
  36. //automatically dumps the argument. 
  37. while(running) 
  38. MessageEnvelope env = (MessageEnvelope)input.Receive(); 
  39. IChannel channel = (IChannel)dictionary[env.ID]; 
  40. channel.send(env.Message); 

6.3 通道事件網關

通道事件網關監聽指定的通道,在接收到消息時觸發一個事件。這個類對于基于事件的程序(例如GUI程序)很有用,或者在使用系統線程池(ThreadPool)來初始化輕量的線程。需要注意的是:使用 WinForms 的程序中你不能在事件處理方法中直接訪問UI控件,只能調用Invoke 方法。因為事件處理方法是由事件網關線程調用的,而不是UI線程。

 

 
  1. public class ChannelEventGateway : SingleRunnable 
  2. private IChannel source; 
  3. public event MessageReceivedEventHandler MessageReceived; 
  4.  
  5. public ChannelEventGateway(IChannel source, bool autoStart, 
  6. bool waitOnStop) : base(true,autoStart,waitOnStop) 
  7. this.source = source; 
  8.  
  9. protected override void Run() 
  10. while(running) 
  11. object c = source.Receive(); 
  12. MessageReceivedEventHandler handler = MessageReceived; 
  13. if(handler != null
  14. handler(this,new MessageReceivedEventArgs(c)); 

7. 比薩外賣店的例子

萬事俱備,只欠東風。我們已經討論了這個同步及消息傳遞框架中的大部分重要的結構和技術(本文沒有討論框架中的其他類如Rendezvous及Barrier)。就像開頭一樣,我們用一個例子來結束這篇文章。這次我們用一個小型比薩外賣店來做演示。下圖展示了這個例子:四個并行進程相互之間進行通訊。圖中展示了消息(數據)是如何使用跨進程通道在四個進程中流動的,且在每個進程中使用了性能更佳的跨線程通道和信箱。

一個進程間通訊同步的C#框架引薦

一開始,一個顧客點了一個比薩和一些飲料。他調用了顧客(customer)接口的方法,向顧客訂單(CustomerOrders)通道發送了一個下單(Order)消息。接單員,在顧客下單后,發送了兩條配餐指令(分別對應比薩和飲料)到廚師指令(CookInstruction)通道。同時他通過收銀(CashierOrder)通道將訂單轉發給收銀臺。收銀臺從價格中心獲取總價并將票據發給顧客,希望能提高收銀的速度 。與此同時,廚師將根據配餐指令將餐配好之后交給打包員工。打包員工處理好之后,等待顧客付款,然后將外賣遞給顧客。

為了運行這個例子,打開4個終端(cmd.exe),用 "PizzaDemo.exe cook" 啟動多個廚師進程(多少個都可以),用 "PizzaDemo.exe backend" 啟動后端進程,用 "PizzaDemo.exe facade" 啟動顧客接口門面(用你的程序名稱來代替 PizzaDemo )。注意:為了模擬真實情景,某些線程(例如廚師線程)會隨機休眠幾秒。按下回車鍵就會停止和退出進程。如果你在進程正在處理數據的時候退出,你將可以在內存轉存報告的結尾看到幾個未處理的消息。在真實世界的程序里面,消息一般都會被轉存到磁盤中,以便下次可以使用。

這個例子使用了上文中討論過的幾個機制。比如說,收銀臺使用一個通道復用器(ChannelMultiplexer)來監聽顧客的訂單和支付通道,用了兩個信箱來實現價格服務。分發時使用了一個通道事件網關(ChannelEventGateway),顧客在食物打包完成之后馬上會收到通知。你也可以將這些程序注冊成 Windows NT 服務運行,也可以遠程登錄后運行。

8. 總結

本文已經討論了C#中如何基于服務的架構及實現跨進程同步和通訊。然后,這個不是唯一的解決方案。例如:在大項目中使用那么多的線程會引來嚴重的問題。這個框架中缺失的是事務支持及其他的通道/信箱實現(例如命名管道和TCP sockets)。這個框架中可能也有許多不足之處。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 国产99久久精品一区二区永久免费 | 久久人人爽爽爽人久久久 | 亚洲 精品 综合 精品 自拍 | 天天拍天天操 | 福利精品在线观看 | 日韩中文字幕在线视频 | www在线观看国产 | 日韩精品久久久久久 | 亚洲精品成人悠悠色影视 | 日韩欧美中文国 | 欧美国产日本 | 国产一区二区精品 | 91蜜桃婷婷亚洲最大一区 | 精品91在线视频 | 免费观看国产黄色 | 97人人爱 | 欧美综合色 | 91精品国产综合久久久久久丝袜 | 日韩久草| 青青免费在线视频 | 在线亚洲天堂 | 黄色av资源 | 亚洲啪视频 | 午夜精品久久久久久久久久久久久 | 久久久久久精 | 欧美日韩系列 | 久久久国产一区二区三区四区小说 | 成人精品一区二区三区中文字幕 | 麻豆精品久久久 | 日本免费三片免费观看 | 黄色小视频在线免费观看 | 手机看片369 | 国产一区二区精品在线 | 在线a级毛片 | 一区亚洲 | 日韩一区二区不卡 | 欧美成人激情视频 | 欧美在线一二三 | 日本在线看片 | www污在线观看| 老妇激情毛片免费 |