Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

dotnet-async-patterns

БесплатноБез исполняемых скриптовНе проверен

Master .NET async/await patterns including Task-based Asynchronous Pattern (TAP), ValueTask optimization, ConfigureAwait usage, cancellation tokens, parallel…

thapaliyabikendraот thapaliyabikendra★ 25 звёзд на GitHub

Об этом скилле

.NET Async/Await Patterns

Master asynchronous programming in .NET for building high-performance, scalable ASP.NET Core applications.

When to Use This Skill

  • Building ASP.NET Core APIs
  • Working with async database operations (EF Core)
  • Calling external APIs or web services
  • Implementing background processing
  • Handling concurrent requests efficiently
  • Preventing thread pool starvation
  • Optimizing application performance
  • Avoiding deadlocks

Core Concepts

1. Async/Await Fundamentals

Basic Async Method:

// Async method signature
public async Task<Patient> GetPatientAsync(Guid id)
{
    var patient = await _dbContext.Patients.FindAsync(id);
    return patient;
}

// Async method without return value
public async Task SendEmailAsync(string to, string subject, string body)
{
    await _emailService.SendAsync(to, subject, body);
}

// Async method with value return
public async Task<int> GetPatientCountAsync()
{
    return await _dbContext.Patients.CountAsync();
}

Calling Async Methods:

// Good: Always await async methods
public async Task<AppointmentDto> CreateAppointmentAsync(CreateAppointmentDto input)
{
    var patient = await _patientRepository.GetAsync(input.PatientId);
    var doctor = await _doctorRepository.GetAsync(input.DoctorId);

    // Validate and create appointment
    var appointment = new Appointment(/*...*/);
    await _appointmentRepository.InsertAsync(appointment);

    return ObjectMapper.Map<Appointment, AppointmentDto>(appointment);
}

// Bad: Blocking async code (causes deadlocks)
public AppointmentDto CreateAppointment(CreateAppointmentDto input)
{
    var patient = _patientRepository.GetAsync(input.PatientId).Result; // DON'T DO THIS
    var doctor = _doctorRepository.GetAsync(input.DoctorId).Wait(); // DON'T DO THIS
    // ...
}

2. ConfigureAwait

Library Code (Use ConfigureAwait(false)):

// In class libraries or reusable components
public async Task<Patient> GetPatientByEmailAsync(string email)
{
    // ConfigureAwait(false) avoids capturing synchronization context
    // Better performance, especially in library code
    var patient = await _dbContext.Patients
        .FirstOrDefaultAsync(p => p.Email == email)
        .ConfigureAwait(false);

    return patient;
}

ASP.NET Core (ConfigureAwait Not Needed):

// In ASP.NET Core controllers/app services
public async Task<ActionResult<PatientDto>> GetPatient(Guid id)
{
    // No need for ConfigureAwait in ASP.NET Core
    // ASP.NET Core doesn't have a synchronization context
    var patient = await _patientRepository.GetAsync(id);
    return Ok(patient);
}

Rule of Thumb:

  • ASP.NET Core: ConfigureAwait not needed
  • Library code: Use ConfigureAwait(false) for performance
  • UI applications (WPF/WinForms): Don't use ConfigureAwait(false)

3. ValueTask for Performance

When to Use ValueTask:

// Use ValueTask when result is often synchronous (cached/immediate)
public ValueTask<Patient> GetPatientAsync(Guid id)
{
    // Check cache first
    if (_cache.TryGetValue(id, out Patient cachedPatient))
    {
        return new ValueTask<Patient>(cachedPatient); // Synchronous return
    }

    // Cache miss, fetch from database
    return new ValueTask<Patient>(FetchPatientFromDatabaseAsync(id));
}

private async Task<Patient> FetchPatientFromDatabaseAsync(Guid id)
{
    return await _dbContext.Patients.FindAsync(id);
}

// Use Task for always-async operations
public async Task<Patient> CreatePatientAsync(CreatePatientDto input)
{
    // Always async, use Task
    var patient = new Patient(/*...*/);
    await _dbContext.Patients.AddAsync(patient);
    await _dbContext.SaveChangesAsync();
    return patient;
}

ValueTask Rules:

  • Don't await ValueTask multiple times
  • Don't call .Result or .GetAwaiter().GetResult()
  • Consider using for hot paths with frequent synchronous returns

4. Cancellation Tokens

Controller with Cancellation:

[HttpGet]
public async Task<ActionResult<List<PatientDto>>> GetPatients(
    CancellationToken cancellationToken) // Automatically bound from request
{
    var patients = await _dbContext.Patients
        .AsNoTracking()
        .ToListAsync(cancellationToken); // Pass token to async operations

    return Ok(patients);
}

Service with Cancellation:

public class AppointmentService : IAppointmentService
{
    public async Task<List<Appointment>> GetUpcomingAppointmentsAsync(
        Guid doctorId,
        CancellationToken cancellationToken = default)
    {
        // Check if cancellation requested
        cancellationToken.ThrowIfCancellationRequested();

        var appointments = await _dbContext.Appointments
            .Where(a => a.DoctorId == doctorId && a.AppointmentDate >= DateTime.Today)
            .ToListAsync(cancellationToken);

        // Long-running operation
        foreach (var appointment in appointments)
        {
            cancellatio
Полный SKILL.md на GitHub

Установить dotnet-async-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл dotnet-async-patterns?

Master .NET async/await patterns including Task-based Asynchronous Pattern (TAP), ValueTask optimization, ConfigureAwait usage, cancellation tokens, parallel processing, and avoiding deadlocks in ASP.NET Core applications for maximum performance and responsiveness.

Как установить скилл dotnet-async-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл dotnet-async-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить dotnet-async-patterns с