我有以下的代碼,並在.NET 4.5C#Task.Run相當於在.NET 4.0中
return Task.Run(async() => await MyAsyncMethodThatReturnsAnObject()).Result;
工作正常,現在我需要它.NET 4.0運行,所以我想出了:
return Task.Factory.StartNew<object>(async() => { await MyAsyncMethodThatReturnsAnObject()}).Result;
但它給我這個錯誤:
'Task<object>' does not contain a definition for GetAwaiter and no extension method 'GetAwaiter' acception the first argument of type 'Task<object>'
MyAsyncMethodThatReturnsAnObject
是一種工廠方法,其返回類型爲object
。
委託'異步()=>等待MyAsyncMethodThatReturnsAnObject()'等同於'工作()=> MyAsyncMethodThatReturnsAnObject()'兩個案例。 – spender
更好的問題是你爲什麼這樣做?你釋放一個線程來阻止另一個? –
@spender你的建議使我的代碼編譯,這是偉大的。但是,當我在調用方中做出相同的更改時,它失敗了:'不能轉換表達式類型'System.Threading.Tasks.Task'返回類型'System.Threading.Tasks.Task