当前位置: 代码网 > it编程>编程语言>Asp.net > c#使用Await异步操作的方法

c#使用Await异步操作的方法

2026年07月19日 Asp.net 我要评论
无参数的操作: private async task docleanup() { int days = (int)numretentiondays.value; var result

无参数的操作:

 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异步操作的方法的文章就介绍到这了,更多相关c# await异步操作内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com