Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

c# - Is it ok to use "async" with a ThreadStart method?

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;
            }
        }
    }
}

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. Is there any reason not to do this?
  2. Is DoWork actually able to run asynchronously, if it's already running inside a dedicated thread?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...