[英]Do multiple awaits to the same Task from a single thread resume in FIFO order?
[英]Is the order of resume multiple await expressions to the same task is guaranteed?
我正在學習使用C#4.5進行異步/等待,並想知道當多個“等待者”正在等待同一任務時會發生什么。
我正在做一些實驗,我想我了解發生了什么。 但是,我有一些問題要問:
看一下這段代碼:
AsyncAwaitExperiment.fxml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace View
{
/// <summary>
/// Interaction logic for AsyncAwaitExperiment.xaml
/// </summary>
public partial class AsyncAwaitExperiment : Window
{
private CancellationTokenSource token;
private Task longRunningTask;
public AsyncAwaitExperiment()
{
InitializeComponent();
}
private void startAsyncOperation(object sender, RoutedEventArgs e)
{
if (longRunningTask != null && !longRunningTask.IsCompleted)
{
return;
}
else
{
longRunningTask = null;
token = new CancellationTokenSource();
}
Action action = () =>
{
while (!token.Token.IsCancellationRequested)
{
Thread.Sleep(100);
}
};
longRunningTask = Task.Factory.StartNew(
action,
token.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Current);
}
private void stopOperation(object sender, RoutedEventArgs e)
{
if (longRunningTask == null
|| longRunningTask.IsCompleted
|| token == null
|| token.Token.IsCancellationRequested)
{
return;
}
token.Cancel();
}
private async void firstAwait(object sender, RoutedEventArgs e)
{
if (longRunningTask == null || longRunningTask.IsCompleted)
return;
await longRunningTask;
Console.WriteLine("First Method");
}
private async void secondAwait(object sender, RoutedEventArgs e)
{
if (longRunningTask == null || longRunningTask.IsCompleted)
return;
await longRunningTask;
Console.WriteLine("Second Method");
}
}
}
AsyncAwaitExperiment.fxml
<Window x:Class="View.AsyncAwaitExperiment"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AsyncAwaitExperiment" Height="300" Width="300">
<Grid>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Content="Start Async" Margin="3" Click="startAsyncOperation" />
<Button Content="Stop Async" Margin="3" Click="stopOperation" />
<Button Content="Await First" Margin="3" Click="firstAwait" />
<Button Content="Await Second" Margin="3" Click="secondAwait" />
</StackPanel>
</Grid>
</Window>
此代碼的行為是:
通過這段代碼和一些斷點,我注意到了一些行為。
問題是:
PS:對不起,我的英語不好:/
您不應對活動的恢復順序承擔任何責任。 假設將來有人設法編寫一個完全是多線程的新UI系統,那么您甚至期望UI線程可以並行運行(注意:沒有人認為編寫多線程UI系統是理智的。當前;即使“同時”恢復執行兩個任務,也可能會無限期地暫停其中一項)
如果有活動之間的依賴關系在你的代碼,使他們明確。 否則,假設它們可能以任何順序發生並且可能被交錯。 那是編程的唯一明智的方法。
最后,沒有。 使用CancellationToken
,就完成了。 如果需要另一個,則需要創建一個新的。 實際上,這使考慮多個任務/活動變得更容易考慮-從取消令牌到取消令牌都不可能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.