暫停異步操作,等待UWP應用中的用戶輸入 本指南演示瞭如何在通用Windows平台(UWP)應用程序中暫時停止執行異步方法,直到觸發特定事件(例如按鈕單擊)。 當長期運行的異步過程(在此示例中
)需要用戶交互之前,這一點特別有用。> GetResults
方法1:使用
>
SemaphoreSlim
類提供直接的信號傳導機制。 這是實施它的方法:
SemaphoreSlim
<code class="language-csharp">private SemaphoreSlim signal = new SemaphoreSlim(0, 1); // Initially 0 permits, max 1 // Event handler to release the semaphore private void buttonContinue_Click(object sender, RoutedEventArgs e) { signal.Release(); } // Asynchronous method pausing for the signal private async Task GetResults() { // ... Perform lengthy operations ... await signal.WaitAsync(); // Pause until the signal is released // ... Continue execution after the event ... }</code>
>
通過創建代表用戶互動的完成的ATaskCompletionSource<bool>
> >提供了一種更靈活的方法。
TaskCompletionSource<bool>
這兩種方法有效地暫停了Task<bool>
的異步操作,直到發生指定事件,避免了效率低下的輪詢技術。 選擇最適合您應用程序的體系結構和復雜性的方法。
以上是如何暫停異步方法執行,直到發生在地鐵應用中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!