![](/img/trans.png)
[英]How can I dynamically read XML files in a folder without refreshing my app using C#?
[英]How can I get a portion of my C# app to load dynamically without app restart?
我的C#應用程序server.exe
對我的業務運營至關重要,理想情況下,它需要24/7不間斷運行。 該代碼固若金湯,但我無法控制的是第三方生成的入站數據提要的質量很差。 我偶爾會收到包含異常的數據提要,在這種情況下,我必須:
server.exe
的提要處理代碼以適應異常 server.exe
並允許處理語法上有缺陷的提要 整個過程通常花費不到幾分鍾,但是server.exe
的重新啟動會導致某些非關鍵狀態信息的重置,更糟糕的是,會導致依賴server.exe.
的外部進程中斷server.exe.
我的目標: 將提要處理代碼隔離到一個單獨的DLL中,無需重新啟動server.exe
即可更新其內容。 我該怎么做呢?
在撰寫此論壇帖子之前,請允許我解釋我到目前為止所做的事情:
提要處理器接口已移至名為common.dll
的新程序集。 該界面如下所示:
public interface IFeedProcessor{
bool ProcessFeed(String filePath); //returns false on failure, true on success
}
Server.exe
現在引用common.dll
。
提要處理器本身已移至名為feedProcessors.dll
的新程序feedProcessors.dll
。 實現看起來像這樣:
internal class FeedProcessor1:IFeedProcessor{
public FeedProcessor1(){}
bool ProcessFeed(String filePath){/*implementation*/return true;}
}
internal class FeedProcessor2:IFeedProcessor{
public FeedProcessor2(){}
public bool ProcessFeed(String filePath){/*implementation*/return true;}
}
[... and so on...]
feedProcessors.dll
還包含一個名為FeedProcessorUtils
的類,該類用於基於一些配置輸入來創建特定的提要處理器。 看起來像這樣:
public class FeedProcessorUtils{
public static void CreateFeedProcessor(int feedType /*and other configuration params*/){
switch(feedType){
case 1:return new FeedProcessor1();
case 2:return new FeedProcessor2();
default: throw new ApplicationException("Unhandled feedType: "+feedType);
}
}
}
一切都像以前一樣工作,但是當然不能解決我的動態加載問題; 如果我使用新代碼更新feedProcessors.dll
並將其復制到生產服務器,則由於文件正在使用中,因此無法執行此操作。 毫不奇怪。 那么解決方案是什么?
理想情況下,我希望能夠將更新的feedProcessors.dll
復制到生產服務器,而不會出現使用中文件錯誤並且無需重新啟動server.exe
。 然后,下次server.exe
調用FeedProcessorUtils.CreateFeedProcessor()時,它將從我修訂的 DLL(而不是舊的DLL)中執行。
我從哪里開始?
您要對動態加載的DLL使用卷影復制程序集http://msdn.microsoft.com/zh-cn/library/ms404279(v=vs.110).aspx
聽起來像是使用MEF的經典場所: http : //msdn.microsoft.com/zh-cn/library/dd460648( v= vs.110).aspx
我建議您調查一下並在繼續進行時提問。
除了卷影復制選項,您還應該創建一個AppDomain並檢查將dll更改為重新啟動域並重新加載dll的時間 ,您可以使用FileSystemWatcher進行檢查。
注意不要在AppDomains之間直接引用您的類 ,否則您的舊程序集將永遠不會被卸載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.