我如何ThreadStart一个标记为异步的方法? [英] How do I ThreadStart a method that is labelled async?

查看:156
本文介绍了我如何ThreadStart一个标记为异步的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个单独的线程上运行一个处理循环:

I want to run a processing loop on a separate thread:

_processingThread = new Thread(new ThreadStart(DoWork)));

但是DoWork需要异步:

But DoWork needs to be async:

private async Task QueueProcessorDoWork()
{
   while (true)
   {
     await something();
   }
}

如何将两者连接在一起?当我添加async Task时,它与ThreadStart的参数不匹配.

How can I connect the two together? When I add async Task, it doesn't match the parameter of ThreadStart.

我认为可以建立设置线程async Task的方法,但是我不确定这是否有帮助.

It is possible to make the method that sets up the thread async Task, I think, but I am not sure if that would help.

这里最好的解决方案是什么?我需要我的线程才能开始运行,然后返回.

What's the best solution here? I need my thread to start running then return.

推荐答案

这将使指定的工作排队在ThreadPool上运行.

This will queue the specified work to run on the ThreadPool.

_ = Task.Run(() => QueueProcessorDoWork());

QueueProcessorDoWork现在必须完全自给自足并照顾好自己.抛出的任何异常都不会被捕获.调用线程无法知道它是否成功.

QueueProcessorDoWork now has to be completely self sufficient and take care of itself. Any exceptions thrown will not be caught. The calling thread has no way of knowing if it's been successful or otherwise.

_ =只是停止编译器警告未等待调用.

The _ = just stops the compiler warning that the call is not awaited.

这篇关于我如何ThreadStart一个标记为异步的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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