C#執行異步操作的幾種方式


//線程異步按鈕

private void ThreadButton_Click(object sender, RoutedEventArgs e)
{
new Thread(o =>
{
var time = TestTask();
Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action<Button, int>(OutputInfo), sender as Button, time);
})
{ IsBackground = true }
.Start();
}

 

//線程池異步按鈕

private void ThreadPoolButton_Click(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(s =>
{
var time = TestTask();
Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action<Button, int>(OutputInfo), sender as Button, time);
});
}

 

//Task異步按鈕

private void TaskButton_Click(object sender, RoutedEventArgs e)
{
var t = new Task<int>(TestTask);
t.ContinueWith(p =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action<Button, int>(OutputInfo), sender as Button, p.Result);
});
t.Start();
}

 

//await異步按鈕

private async void AwaitButton_Click(object sender, RoutedEventArgs e)
{
Task<int> t = new Task<int>(TestTask);
t.Start();
var time = await t;
OutputInfo(sender as Button, time);
//var time = await TestTaskAsync();
//OutputInfo(sender as Button, time);
}

 

//線程異步性能測試

private void ThreadTest_Click(object sender, RoutedEventArgs e)
{
var time = AsyncTest(new Action(() => ThreadButton_Click(ThreadButton, null)));
ShowTestResult(sender, time);
}

 

//線程池異步性能測試

private void ThreadPoolTest_Click(object sender, RoutedEventArgs e)
{
var time = AsyncTest(new Action(() => ThreadPoolButton_Click(ThreadPoolButton, null)));
ShowTestResult(sender, time);
}

 

//Task異步性能測試

private void TaskTest_Click(object sender, RoutedEventArgs e)
{
var time = AsyncTest(new Action(()=> TaskButton_Click(TaskButton, null)));
ShowTestResult(sender, time);
}

 

//await異步性能測試

private void AwaitTest_Click(object sender, RoutedEventArgs e)
{
var time = AsyncTest(new Action(() => AwaitButton_Click(AwaitButton,null)));
ShowTestResult(sender, time);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM