在另一个窗口中的异步功能

发布于 2025-02-06 06:16:22 字数 700 浏览 0 评论 0原文

我在运行ASYNC功能时遇到问题。我正在尝试进行异步调用,以设置一些Timmers来运行一些代码。我已经尝试使功能异步,我觉得自己做错了什么。我已经将功能范围缩小到两个功能,并在功能中添加了20秒的睡眠以测试问题,我想知道我的睡眠是否在暂停整个应用程序,还是我不正确地进行异步?正确方向的任何点都会有所帮助。先感谢您。

private async void RunAsyncExample(){
    Task timersTask = mainWindow.StartTimers();   //This has a 20 sec sleep
    mainWindow.PullReceipt(handoff);              //This should not wait
    await timersTask;                             //This should wait
}

以下是mainwindow.starttimers

public async Task<Task> StartTimers()
{
    _log.LogError("starting timer");
    System.Threading.Thread.Sleep(20000);
    _log.LogError("ending timer");
    return Task.CompletedTask;
}

I'm having issues with running a function as async. I'm trying to make an async call to set up some timmers to run some code. I've tried making the function async and I feel like I'm doing something wrong. I've narrowed down the functionality to two functions and added a 20-second sleep in the function to test out the issue and I'm wondering if my sleep is pausing the whole application or am I doing async incorrectly? Any point in the right direction would be helpful. Thank you in advance.

private async void RunAsyncExample(){
    Task timersTask = mainWindow.StartTimers();   //This has a 20 sec sleep
    mainWindow.PullReceipt(handoff);              //This should not wait
    await timersTask;                             //This should wait
}

Below is the mainWindow.StartTimers

public async Task<Task> StartTimers()
{
    _log.LogError("starting timer");
    System.Threading.Thread.Sleep(20000);
    _log.LogError("ending timer");
    return Task.CompletedTask;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小梨窩很甜 2025-02-13 06:16:22

尝试以下操作:

public async Task StartTimers()
{
    _log.LogError("starting timer");
    await Task.Delay(20000);
    _log.LogError("ending timer");
}

顺便说一句,您的代码有很多问题:

  • 声明async方法。
  • 如果不等待 ,您不应
  • 您应该在UI外放置非UI代码
  • ,应该正确命名方法。 startTimers没有启动任何计时器,因此它不是适当的名称。
  • async void仅适用于异步事件处理程序

Try the following:

public async Task StartTimers()
{
    _log.LogError("starting timer");
    await Task.Delay(20000);
    _log.LogError("ending timer");
}

Incidentally, your code has many issues:

  • You should not declare an async method if it doesn't await
  • You should not Sleep
  • You should put non UI code outside UI
  • You should name methods properly. StartTimers doesn't start any timer, so it is not an appropriate name.
  • async void is appropriate only for asynchronous event handlers
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文