C# 多執行緒程(Multithreading)【五】task

Task 是非同步程式設計(asynchronous programming)的一個核心概念,它代表一個非同步操作。

用來表示非同步工作的類別,實現非同步處理、平行運算、不阻塞 UI。

命名空間System.Threading.Tasks


在 C# 中常見的定義方式如下:

Task t = Task.Run(() => {
// 一些要背景執行的工作
Debug.WriteLine("背景執行的程式碼");
});

如果這個背景工作會傳回一個結果,例如整數,則會使用泛型版本 Task<T>

Task<int> t = Task.Run(() => {
return 42;
});


非同步處理資料、不中斷主執行緒

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;//for Debug.WriteLine
class Program
{
static void Main()
{
Debug.WriteLine("主執行緒開始");
Task.Run(() =>
{
Debug.WriteLine("資料處理開始");
Thread.Sleep(2000); // 模擬資料處理
Debug.WriteLine("資料處理完成");
});
// 主執行緒仍然可以繼續工作
for (int i = 0; i < 5; i++)
{
Debug.WriteLine("主執行緒仍在執行中...");
Thread.Sleep(500);
}
Debug.WriteLine("主執行緒結束");
}
}
  • Task.Run(...):啟動一個新的非同步工作。
  • Thread.Sleep(...):模擬一個耗時的處理(例如存取資料庫、網路請求等)。
  • ContinueWith(...):當上面的任務完成後再執行。
  • task.Wait():主執行緒等待該 Task 完成,避免主程式提早結束。

非阻塞主執行緒

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;//for Debug.WriteLine
class Program
{
static void Main()
{
Debug.WriteLine("主執行緒開始");
// 啟動一個非同步任務,不會阻塞主執行緒
Task.Run(() =>
{
Debug.WriteLine("背景工作開始執行...");
Thread.Sleep(3000); // 模擬耗時操作
Debug.WriteLine("背景工作結束");
})
.ContinueWith(t =>
{
Debug.WriteLine("後續處理完成");
});
// 主執行緒繼續執行,不等待上面的任務
for (int i = 0; i < 5; i++)
{
Debug.WriteLine($"主執行緒正在執行其他工作... {i}");
Thread.Sleep(500);
}
Debug.WriteLine("主執行緒結束");
}
}
  • 背景任務透過 Task.Run 執行
  • ContinueWith task結束後,可接後續任務執行

多個任務平行執行

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;//for Debug.WriteLine
class Program
{
static void Main()
{
Debug.WriteLine("主執行緒啟動");
for (int i = 1; i <= 3; i++)
{
int taskNum = i;
Task.Run(() =>
{
Debug.WriteLine($"Task {taskNum} 開始");
Thread.Sleep(1000 * taskNum); // 模擬不同時間長度
Debug.WriteLine($"Task {taskNum} 結束");
});
}
Debug.WriteLine("主執行緒正在執行其他事");
}
}

從非同步任務中回傳資料

雖然不能 await 結果,但你可以使用 ContinueWith 來處理結果。

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;//for Debug.WriteLine
class Program
{
static void Main()
{
Debug.WriteLine("主執行緒開始");
Task task = Task.Run(() =>
{
Thread.Sleep(1500);
return 42; // 模擬計算後回傳的資料
});
task.ContinueWith(t =>
{
Debug.WriteLine($"收到非同步結果:{t.Result}");
});
Debug.WriteLine("主執行緒繼續執行");
}
}

模擬非同步下載

using System;
using System.Net;
using System.Threading.Tasks;
using System.Diagnostics;//for Debug.WriteLine
class Program
{
static void Main()
{
Debug.WriteLine("開始模擬下載");
Task.Run(() =>
{
using (WebClient client = new WebClient())
{
string data = client.DownloadString("https://example.com");
Debug.WriteLine("下載完成,內容長度:" + data.Length);
}
});
Debug.WriteLine("主執行緒不中斷,繼續執行其他工作");
}
}

非同步排程(定時任務)

using System;
using System.Threading.Tasks;
using System.Diagnostics;//for Debug.WriteLine
class Program
{
static void Main()
{
Debug.WriteLine("開始排程任務");
Task.Run(() =>
{
while (true)
{
Debug.WriteLine("定時任務執行中:" + DateTime.Now);
Task.Delay(2000).Wait(); // 每 2 秒執行一次
}
});
Debug.WriteLine("主執行緒自由運作");
}
}

留言

2025

05-27C# 多執行緒程(Multithreading)【五】task
05-21C# 多執行緒程(Multithreading)【四】ThreadPool
05-19C# 多執行緒程(Multithreading)【三】UI操作
05-19C# 多執行緒程(Multithreading)【二】Thread
05-12C# 多執行緒程(Multithreading)【一】
05-05WMI (Windows管理規範)與WQL(WMI 查詢語言)
04-30WndProc 視窗處理函數【三】USB裝置插入/移除偵測
04-29WndProc 視窗處理函數【二】Windows Messages (WM_*) 分類清單
04-29WndProc 視窗處理函數【一】

2024

11-27SPI Flash 操作 (Read/Write/Erase)
11-19Rotary Encoder Switch 旋轉編碼開關
11-14Command Line Interface - CLI via UART
11-14【STM32】USB HID - Volume Control
11-13【STM32】USB Custom HID
11-12【STM32】USB HID Keyboard + Mouse
11-12【STM32】USB HID Keyboard
11-12【STM32】USB HID Mouse
10-15SSD1306 128x64 OLED 【五】Wokwi Animator
09-2432F429IDISCOVERY - - LTDC [3] + FMC (SDRAM) + FatFS
09-2432F429IDISCOVERY - - LTDC [2] + FMC (SDRAM)
09-20STM32 + FatFs + SD card via SPI【三】FatFS指令操作II
09-19STM32 + FatFs + SD card via SPI【二】FatFS指令操作
09-18STM32 + FatFs + SD card via SPI【一】移植FatFS
09-0232F429IDISCOVERY - - LTDC [1]
04-17SSD1306 128x64 OLED 【四】Adafruit / GFX Library
04-17Arduino - Serial Plotter繪圖儀
04-16SSD1306 128x64 OLED 【三】
04-15SSD1306 128x64 OLED 【二】 Datasheet
04-12SSD1306 128x64 OLED 【一】I2C版本
03-20【freeRTOS】vTaskDelay 與 vTaskDelayUntil 的差異
03-19【freeRTOS】API功能列表
03-18【freeRTOS】Day1
03-08MBR和Blank project的差別
03-05刪除註冊檔registry的資料
02-27DFU over Bluetooth Low Energy
02-27nRF Util - 使用手冊
02-26nRF Command Line Tools
02-20建立BootLoader settings
02-19Secure DFU packet (ZIP) build 建立含袐鑰的Zip檔
02-19Secure DFU via BLE
02-19Secure DFU via UART
02-16nRF Util 安裝
01-16nRF52840 ic升級成nRF52840 Dongle的程式

2023

11-21[ SEGGER Embedded Studio ] 新增header files
11-21[ SEGGER Embedded Studio ] 編譯nRF52840時遇到的問題
11-07Arduino Nano ESP32 - Debugging除錯模式
11-03Git快速入手 - 使用Git GUI
10-30Git快速入手 - 使用Git Bash
10-12程式碼高亮顯示 -- google-code-prettify

2022

11-30[EZ-PD] CCG6DF CCG6SF的Host SDK遇到編譯錯誤(一)

2019

05-27[ Eagle PCB ] 合板成品
05-23#CASE_001_USB_TOOL_RL78_G12
05-22[ Eagle PCB ] 初次洗板
05-21[ Eagle PCB ] Panelize 併板
05-20[ Eagle PCB ] 建立自己的Library及元件
05-20[ Eagle PCB ] 添加library及元件
05-20[ Eagle PCB ] Introduce

2018

04-25[ TCP test Tool ] 好用的TCP Server/Client工具
01-16RZ/A1H -[0]- Renesas RZ/A1H YR0K77210S009BE BSP環境架設

2017

12-11EZ USB Suit使用JLink online debug FX3
10-20RL78 -[12]- CS+_CACX_Lab5_LowPower mode
10-16RL78 -[11]- CS+_CACX_Lab4_ADC_溫度感測
10-13RL78 -[10]- CS+_CACX_Lab4_ADC_內部參考電壓
10-13RL78 -[9]- CS+_Lab3_I2C + MPU6050
10-13RL78 -[8]- CS+_Lab2_Uart transmit
10-12RL78 -[7]- Renesas Flash Programmer 獨立燒錄軟體
10-12RL78 -[6]- CS+_雜記
10-12RL78 -[5]- CS+_tracking variables on debug mode
10-12RL78 -[4]- CS+_顯示ROM與RAM的使用size
10-12RL78 -[3]- CS+_Lab1_Led blinking
10-12RL78 -[2]- CS+專案建立
10-12RL78 -[1]- 開發環境介紹
10-06ESP-01 -[0]- 硬體設置
10-06LinkIt 7688 program Renesas RL78/G12 by 1-wire
10-06LinkIt Smart 7688 -[3]- Build the firmware from source codes
10-06LinkIt Smart 7688 -[2]- 使用UART進入bootloader / kernel console
10-06LinkIt Smart 7688 -[1]- 使用SSH連接kernel console
10-06LinkIt Smart 7688 -[0]- 初次使用
07-14LinkIt Smart 7688 -[9]- Using MRAA SPI in Python
07-13LinkIt Smart 7688 -[8]- Using MRAA UART in Python
07-12LinkIt Smart 7688 -[7]- Using MRAA I2C in Python
07-12LinkIt Smart 7688 -[6]- Using MRAA PWM in Python
07-12LinkIt Smart 7688 -[5]- Using MRAA GPIO in Python
07-10LinkIt Smart 7688 -[4]- 雜記
06-29輕乳酪蛋糕 Cotton Cheesecake
06-26VirtualBox 的 Ubuntu與Windows 共用資料夾

2015

04-29偵測USB PnP