async-programming-skill
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAsync Programming
异步编程
Purpose
用途
Async/await enables non-blocking concurrent operations. This skill documents patterns for safe async code.
async/await 支持非阻塞并发操作。本技能记录了编写安全异步代码的模式。
When to Use
使用场景
Use this skill when:
- Working with I/O operations
- Building concurrent systems
- Managing timeouts
- Implementing cancellation
在以下场景中使用本技能:
- 处理I/O操作时
- 构建并发系统时
- 管理超时机制时
- 实现取消操作时
Key Patterns
核心模式
1. All I/O is Async
1. 所有I/O操作均为异步
Never use blocking I/O:
python
undefined切勿使用阻塞式I/O:
python
undefinedWRONG
WRONG
with open(file) as f:
data = json.load(f)
with open(file) as f:
data = json.load(f)
CORRECT
CORRECT
async with aiofiles.open(file) as f:
data = await f.read()
undefinedasync with aiofiles.open(file) as f:
data = await f.read()
undefined2. Timeout Protection
2. 超时保护
All async operations need timeouts:
python
try:
result = await asyncio.wait_for(operation(), timeout=30.0)
except asyncio.TimeoutError:
# Handle timeout所有异步操作都需要设置超时:
python
try:
result = await asyncio.wait_for(operation(), timeout=30.0)
except asyncio.TimeoutError:
# Handle timeout3. Error Handling
3. 错误处理
Async operations need proper error handling:
python
async def safe_operation():
try:
return await risky_operation()
except Exception as e:
logger.error(f"Operation failed: {e}")
raise TradingError(...) from e异步操作需要适当的错误处理:
python
async def safe_operation():
try:
return await risky_operation()
except Exception as e:
logger.error(f"Operation failed: {e}")
raise TradingError(...) from eSee Also
另请参阅
- Python asyncio: https://docs.python.org/3/library/asyncio.html
- Python asyncio: https://docs.python.org/3/library/asyncio.html