可以使用“async"吗?使用 ThreadStart 方法? [英] Is it ok to use "async" with a ThreadStart method?

查看:28
本文介绍了可以使用“async"吗?使用 ThreadStart 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows 服务,它使用 Thread 和 SemaphoreSlim 每 60 秒执行一些工作".

I have a Windows Service that uses Thread and SemaphoreSlim to perform some "work" every 60 seconds.

class Daemon
{
    private SemaphoreSlim _semaphore;
    private Thread _thread;

    public void Stop()
    {
        _semaphore.Release();
        _thread.Join();
    }

    public void Start()
    {
        _semaphore = new SemaphoreSlim(0);
        _thread = new Thread(DoWork);
        _thread.Start();
    }

    private void DoWork()
    {
        while (true)
        {
            // Do some work here

            // Wait for 60 seconds, or exit if the Semaphore is released
            if (_semaphore.Wait(60 * 1000))                
            {
                return;
            }
        }
    }
}

我想从 DoWork 调用一个异步方法.为了使用 await 关键字,我必须将 async 添加到 DoWork:

I'd like to call an asynchronous method from DoWork. In order to use the await keyword I must add async to DoWork:

private async void DoWork()

  1. 有什么理由不这样做吗?
  2. 如果 DoWork 已经在专用线程中运行,它真的能够异步运行吗?

推荐答案

可以这样做,但这不是一个好主意.一旦第一个 await 未同步完成,其余的工作将在 continuation 上完成,而不是您启动的线程 (_thread);您启动的线程将在第一个这样的 await 处终止.无法保证延续会返回到原始线程,并且在您的场景中,它不能 - 该线程现在是 toast.这意味着:

You can do this, but it wouldn't be a good idea. As soon as the first await hits that is not synchronously completed, the rest of the work will be done on a continuation, not the thread you started (_thread); the thread you start will terminate at the first such await. There is no guarantee that a continuation will go back to the originating thread, and in your scenario, it cannot - that thread is now toast. That means that:

  1. _thread 没有意义,不代表操作的状态;因此,带有 _thread.Join();Stop() 方法不会执行您期望的操作
  2. 您已经创建了一个线程(分配线程的开销很大,尤其是因为堆栈的大小)却让它几乎立即退出
  1. _thread is meaningless and does not represent the state of the operation; as such, your Stop() method with a _thread.Join(); doesn't do what you expect it to do
  2. you've created a thread (allocating threads is expensive, in particular because of the size of the stack) only to have it exit almost immediately

通过使用Task.Run来启动这样的操作,可以避免这两个问题.

Both of these issues can avoided by using Task.Run to start such operations.

这篇关于可以使用“async"吗?使用 ThreadStart 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆