可以使用“异步"功能吗?使用ThreadStart方法? [英] Is it ok to use "async" with a ThreadStart method?
问题描述
我有一个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()
- 有什么理由不这样做吗?
- 如果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:
-
_thread
是没有意义的,不代表操作状态;因此,带有_thread.Join();
的Stop()
方法不能实现您期望的效果 - 您已经创建了一个线程(分配线程非常昂贵,特别是由于堆栈的大小),只是让它几乎立即退出
_thread
is meaningless and does not represent the state of the operation; as such, yourStop()
method with a_thread.Join();
doesn't do what you expect it to do- 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屋!