簡體   English   中英

C#MEF:線程安全導出

[英]C# MEF: Threadsafe Export

假設我有一個CarSystem類,其中有一個CarParts對象集合。 現在,我希望為系統編寫一個立體聲插件,並且希望所有插件的格式為:

public interface ICarPluginMetaData
{
  string Name {get;}
  string Description {get;}
  int Status {get; set;}
}

public interface ICarPlugin
{
  void int setStatus(int newStatus);
}

[Export(typeof(ICarPlugin))]
[ExportMetaData("Name", "Stereo")]
[ExportMetaData("Description","Plays music")]
[ExportMetaData("Status", 0)]
public class StereoPlugin : ICarPlugin
{
  [ICarPluginImport("FrontSpeakers")]
  public CarPart myFrontSpeakersPointer;

  [ICarPluginImport("RearSpeakers")]
  public CarPart myRearSpeakersPointer;

  [ICarPluginImport("subwoofer")]
  public CarPart mysubwooferPointer;

  [Export]
  public void setStatus(int newStatus)
  {
    Status = newStatus;
  }
}

現在在我的CarSystem類中,我定義了導出,但是默認行為是創建1個靜態對象,並將其交給所有導入該對象的對象。 我將如何執行以下操作:

[ExportAsThreadsafe]
public CarPart FrontSpeakers

[ExportAsThreadsafe]
public CarPart RearSpeakers

[ExportAsThreadsafe]
public CarPart Subwoofer

[ExportAsThreadsafe]
public CarPart DashLights

這樣,當我創建在單獨線程上運行的第二個插件時,是否獲得了到所有插件的實際對象的線程安全連接?

在MEF中提供線程安全的一種方法是在每個線程中執行單獨的獨立MEF組合。 然后,在該組合中構造的所有內容都在該線程本地。 任何跨線程訪問都在您的控制之下,並且您可以使用常規的線程安全技術。

我不清楚您是否要加載多個立體聲插件並使它們可用於/綁定到一個全局CarSystem,或者您是否只是在談論在彼此獨立的不同線程中具有多個CarSystem。 您可以通過MEF將CarSystem與線程內的特定立體聲插件組合在一起來完成后者。

這是我最終所做的(使用偽代碼):

 Foreach plugin dynamically loaded { //Via reflection Foreach field in the plugin { See if the field has an attribute attached Find the field who's name is the same as it's attribute's name { Using some lookup method, find the object in the CarSystem collection who's name is the same as the attribute name. create a concurrencyQueue using proxy object call field.SetValue(pluginObject, new Proxy Object) //Reflection call } } } 

我基本上說過:“自動執行此操作的MEF螺釘”,並使用反射和自定義屬性自己完成。 我使用MEF進行單向消息傳遞,但是對於需要在CarSystem中更改對象的插件,我使用了自定義的“ MEF”樣式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM