2011-11-03 27 views
1

我有一個RESTful WCF服務,有一個服務方法說BeginX()是WebOperationContext中的靜態函數嗎?

在BeginX中,我在靜態幫助器類中調用我的靜態驗證函數。在靜態Validate方法內部,我可以調用WebOperationContext.Current.OutgoingResponse.StatusCode = blah?

當我的服務中的靜態方法中調用當前上下文時,期望的行爲是什麼?

(我試過原型,但我似乎無法得到WebOperationContext當我嘗試從我的控制檯應用程序運行的進程內WCF服務得到它)

回答

2

WebOperationContext.Current是一個靜態屬性,並且只要方法在該線程上運行,就可以使用任何靜態或其他方法。

private static void CheckWebOperationContext() 
{ 
    Trace.WriteLine(string.Format("CheckWebOperationContext: {0}", WebOperationContext.Current == null ? "WebOperationContext is null" : "WebOperationContext is not null")); 

} 

[OperationContract] 
[WebInvoke] 
public void DemonstrateWebOperationContext() 
{ 
    Trace.WriteLine(string.Format("GetPlayerStatus: {0}", WebOperationContext.Current == null ? "WebOperationContext is null" : "WebOperationContext is not null")); 
    CheckWebOperationContext(); 
    // Now call the same function on a different thread 
    Action act =() => 
     { 
      CheckWebOperationContext(); 
     }; 
    var iAsyncResult = act.BeginInvoke(null, null); 
    iAsyncResult.AsyncWaitHandle.WaitOne(); 
} 

這將導致以下輸出:

GetPlayerStatus:WebOperationContext不爲空

CheckWebOperationContext:WebOperationContext不爲空

CheckWebOperationContext:WebOperationContext爲null

CheckWebOperationContext的第一個調用位於同一個線程中,因此可以使用上下文。 第二次調用是在不同的線程上,所以上下文不可用。