您的位置:首页 > 手游攻略 > c#使用Await异步操作的做法使用教程与实战指南实用指南

c#使用Await异步操作的做法使用教程与实战指南实用指南

作者:互联网  时间: 2026-10-24 15:30:02  

平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“c#采用Await异步操作的做法”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。

无参数的操作:

 private async Task DoCleanup()
 {
     int days = (int)numRetentionDays.Value;

     var result = MessageBox.Show(
         $"确认删除 {days} 天前的历史数据?n此操作不可恢复!",
         "确认清理",
         MessageBoxButtons.YesNo,
         MessageBoxIcon.Warning);

     if (result != DialogResult.Yes) return;

     btnClean.Enabled = false;
     progressBar.Visible = true;
     lblStatus.Text = "正在清理中...";

    await Task.Run(() =>
     {
         DeletedCount = _storageService.CleanOldData(days);
     });

     progressBar.Visible = false;
     btnClean.Enabled = true;

     MessageBox.Show(
         $"清理完成!n共删除 {DeletedCount} 条历史数据。",
         "清理完成",
         MessageBoxButtons.OK,
         MessageBoxIcon.Information);

     DialogResult = DialogResult.OK;
     Close();
 }

调用的方法(按钮事件):

  btnClean.Click += async (s, e) => await DoCleanup();

其中多线程操作为:

 await Task.Run(() =>
     {
         DeletedCount = _storageService.CleanOldData(days);
     });

带参数的异步操作方法:

  /// <summary>
  /// 云端登录验证(返回完整用户信息)
  /// </summary>
  public async Task<CloudLoginResult> CloudLoginAsync(string username, string password)
  {
      try
      {
          var request = new { username, password };
          var content = new StringContent(
              JsonSerializer.Serialize(request, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }),
              Encoding.UTF8,
              "application/json");

          var response = await _httpClient.PostAsync($"{_apiBaseUrl}/api/v1/auth/client-login", content);

          if (response.IsSuccessStatusCode)
          {
              var json = await response.Content.ReadAsStringAsync();
              var result = JsonSerializer.Deserialize<CloudLoginResponse>(json, new JsonSerializerOptions
              {
                  PropertyNameCaseInsensitive = true
              });

              if (result != null && result.Success && result.User != null)
              {
                  return new CloudLoginResult
                  {
                      Success = true,
                      User = result.User
                  };
              }
          }
          return new CloudLoginResult { Success = false, Message = "用户名或密码错误" };
      }
      catch (Exception ex)
      {
          return new CloudLoginResult { Success = false, Message = $"网络异常: {ex.Message}" };
      }
  }

调用方法:

CloudLoginResult cloudResult = await _cloudSyncService.CloudLoginAsync(username, password);

实际处理时,总的来说,c# Await异步操作适合结合实际项目边做边理解。先抓住核心思路,再逐步补上细节和边界处理,最后效果会更稳定,也更容易复用。

相关资讯

最新游戏

更多

Copyright©2010-2019. All rights reserved | 波波三国游戏官网|[email protected]

备案编号:湘ICP备2022015115号-4