[英]Equivalent of F# StartImmediate
是否有可以在Task
上執行的F#的StartImmediate
的C#等效項? 我遇到的情況是有時需要等待一個函數,但是有時我只希望該方法不使用await
即可回調UI線程。
我想盡可能避免異步無效。
例:
public async void DoSomething()
{
//before runs on UI thread
await OtherThing();
//after runs on UI thread
}
public async Task DoSomethingElse()
{
//before runs on UI thread
await OtherThing();
//I want this to run on the UI thread
}
public void CallDoSomething()
{
DoSomething(); //no need to await, returns to the UI thread to continue execution
DoSomethingElse();//Doesn't return to the UI thread to continue execution
DoSomethingElse().???(); // how to return to the UI thread for the async callback?
}
在F#中,它看起來像這樣:
let CallDoSomething () =
//more code here
async {
//runs on the current thread
do! OtherThing()
//runs on the current thread
} |> Async.StartImmediate
//code here doesn't wait for the async to finish
因此,在查看您的代碼示例時。 您有一個async
方法返回Task
。 您正在調用該方法,然后在生成的任務上調用Start
(而不調用await
)。 這將在運行時引發異常。 僅通過調用該方法即可啟動該任務。 啟動已經運行的任務(或完成的任務,如果在返回之前已完成),將引發異常。 您只能Start
使用的Task
構造函數創建的Task
。
您還聲稱,在調用DoSomethingElse
后返回時,您已在注釋中聲明您不在UI線程中。 那是錯誤的。 該代碼將在UI線程中運行。
您還暗示DoSomethingElse
中的await
不會編組UI線程的回調,但是會 。 由於是從UI線程調用的,因此它捕獲了UI上下文,並在調用await
時使用它。
簡而言之,除了刪除對Start
的調用之外,您無需執行任何其他操作。
如果您這樣構造代碼,您確實遇到的一個問題是您將永遠不會知道代碼是否出錯,因為沒有什么可以觀察到任何異常。 有兩種解決方法。 一種方法是讓您在此庄園中調用的每種方法都將自己視為“頂級方法”,並處理所有異常,而不是每次拋出任何異常。
另一個選擇是存儲以這種方式調用的所有任務,然后await Task.WhenAll
這些任務,這樣您就可以在完成所有錯誤時觀察到它們。
您是否嘗試過Task類的RunSynchronously()方法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.