簡體   English   中英

protobuf-net線程安全嗎?

[英]Is protobuf-net thread safe?

我注意到,當我在多線程上下文中使用 protobuf-net 時,它往往會間歇性地失敗並出現以下錯誤:

System.TimeoutException: Timeout while inspecting metadata; this may indicate a deadlock. 
This can often be avoided by preparing necessary serializers during application initialization, rather than allowing multiple threads to perform the initial metadata inspection

但是,如果我在第一次序列化特定類型時鎖定對 protobuf-net 序列化程序的訪問,它就不會失敗。

protobuf-net 是線程安全的,還是這只是一個錯誤?

Protobuf的元數據檢查不是線程安全的。 這個錯誤是“罕見的”,但在並行完成的大型序列化中會發生很多。 我在我的項目中遇到了這個確切的錯誤,我將序列化了大約7000萬個對象。 您可以通過生成序列化的元數據AHEAD來修復它:

Serializer.PrepareSerializer<YourCustomType1>();
Serializer.PrepareSerializer<YourCustomType2>();

在序列化之前的某個地方執行該代碼,可能是靜態構造函數,用於序列化的每個自定義類型。

您還可以嘗試增加Protobuf的元數據檢查超時以嘗試幫助您,但是如果Protobuf代碼中存在真正的死鎖,這實際上只會延遲您的異常:

// Initialize Protobuf Serializer for 5 minutes of wait in the case of long-waiting locks
RuntimeTypeModel.Default.MetadataTimeoutMilliseconds = 300000;

當我第一次遇到 protobuf-net 的線程相關問題時, Haney 的回答對我有所幫助,但后來我注意到當多個線程序列化我們的數據結構時出現奇怪的行為。 更准確地說,序列化仍然成功,但之后無法正確反序列化輸出(這違背了目的)。 反序列化對象的所有成員都是默認值/未初始化值。

我最終使用SemaphoreSlim來確保一次只有 1 個線程可以訪問序列化代碼。 通過該修復,一切都正常運行(我可以忍受等待信號量的延遲)。

暫無
暫無

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

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