當訊息體積超過 64KB 預設限制,或傳輸大型檔案、影音串流、報表輸出時,緩衝模式會導致記憶體壓力劇增、延遲飆升。WCF 的 Streamed 傳輸模式採用串流處理,邊讀邊傳,大幅降低記憶體佔用與首包延遲。
僅支援 BasicHttpBinding、NetTcpBinding、NetNamedPipeBinding。不可使用 WSHttpBinding、WSDualHttpBinding、WSFederationHttpBinding。同時不支援 Reliable Messaging,若需訊息級安全需改用傳輸級安全(HTTPS/SSL)。
Stream、MemoryStream、FileStream(僅作為實作傳回 Stream)FileStream 型別(用戶端會收到 null)Stream.Length 屬性不支援序列化,用戶端呼叫會拋出 NotSupportedException// 正確:介面定義回傳 Stream,實作回傳 FileStream
[OperationContract]
Stream DownloadFile(string fileName);
public Stream DownloadFile(string fileName)
{
return new FileStream(path, FileMode.Open, FileAccess.Read); // 隱含轉型
}
// 用戶端:只能接 Stream,不可強轉 FileStream
Stream stream = proxy.DownloadFile("report.pdf");
| 模式 | 適用方向 | 說明 |
|---|---|---|
| Streamed | 雙向 | 請求與回應皆為串流 |
| StreamedRequest | 上傳 | 請求串流,回應緩衝 |
| StreamedResponse | 下載 | 請求緩衝,回應串流 |
超過限制拋出 CommunicationException。必須依實際檔案大小調整(最大 Int64.MaxValue):
// 程式碼設定
binding.MaxReceivedMessageSize = 100_000_000; // 100MB
// 組態設定
<binding maxReceivedMessageSize="100000000" />
一個作業只能包含一個 Stream 相關參數(含回傳值、out/ref 參數)。以下皆錯誤:
void Upload(Stream s1, Stream s2); // 兩個 Stream
void Upload(Stream s1, out Stream s2); // out Stream
void Upload(Stream s1, ref Stream s2); // ref Stream
Stream Download(Stream stream); // 參數與回傳皆為 Stream
BasicHttpBinding:不支援 SessionNetTcpBinding/NetNamedPipeBinding:雖支援 Session,但 Stream 模式強制 PerCall,OperationContext.Current.SessionId 為 nullSessionMode.Required,否則拋出例外<basicHttpBinding>
<binding name="LargeFileBinding"
transferMode="Streamed"
messageEncoding="Text"
textEncoding="utf-8"
maxReceivedMessageSize="9223372036854775807"
sendTimeout="00:10:00"
receiveTimeout="00:10:00">
</binding>
</basicHttpBinding>
MaxBufferSize 設為 64KB-256KB 平衡記憶體與效能Begin/End 或 async/await 避免阻塞執行緒WCF Stream 操作雖有諸多限制,但掌握「單一 Stream、正確繫結、TransferMode、MaxReceivedMessageSize」四大核心要素,即可構建高效能、低記憶體佔用的大型資料傳輸服務。記住:介面定義 Stream,實作用 FileStream,用戶端收 Stream,勿用 Length。