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

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

问题描述

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

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处终止.无法保证延续将返回到原始线程,并且在您的方案中不能-该线程现在是敬酒的.这意味着:

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.

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

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