如何在同一个线程中运行任务? [英] how to run Tasks in the same thread?

查看:122
本文介绍了如何在同一个线程中运行任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在界面后面抽象WPF:Dispatcher.BeginInvoke()。



我想提供一个基于任务的版本(用于命令行测试,没有UI)在同一个线程中运行所有BeginInvoke()。

任务是否适合该任务?如何使所有运行在同一个线程?

解决方案

同一个线程中的所有BeginInvoke是荒谬的。 BeginInvoke 将始终委托您的委托参数调用到UI线程,如果是,由于一些奇怪的原因,它本身在UI线程中被调用,它将起作用,但是没有实际意义,只会创造一个无用的间接水平。



任务是否恰当?适合什么?这取决于。如果你解释了一些人或我可能会建议你的真实目标。但是你指定了一些想象中的或可能只是解释不佳的目标。没有任何任务。使用一种或另一种技术的想法不是目标。如果你想要实现某些目标,你应该更好地避免将你的问题与你如何实现这一点的想法混在一起。然而,这又取决于。



为了让您明白调用的想法,请阅读我过去的答案:

Control.Invoke()与Control.BeginInvoke() [ ^ ],

Treeview扫描仪和MD5的问题 [< a href =http://www.codeproject.com/Answers/159938/Problem-with-Treeview-Scanner-And-MD5#answer2target =_ blanktitle =New Window> ^ ] 。



对于自定义任务调度程序,它很少有用: https://msdn.microsoft.com/en-us/library/ee789351%28v=vs.110%29.aspx [ ^ ]。



我真的怀疑即使在你意识到自己真正的目标之后,它也会对你有所帮助。再次,这取决于。



真的需要深入了解这个主题,使用这种方法正确设计代码。



-SA


找到方法!

使用 LimitedConcurrencyLevelTask​​Scheduler MSDN 上找到的课程[ ^ ] !! :d

I am abstracting WPF: Dispatcher.BeginInvoke() behind an interface.

I want to provide a Task based version (for command line test, without UI) that run all BeginInvoke() in the same thread.
Would Task be appropriate to the task? How to make all run in the same thread?

解决方案

"All BeginInvoke in the same thread" is absurd. BeginInvoke will always delegate your delegate parameter to be called to UI thread, and, if it is, by some weird reason, is itself called in the UI thread, it will work, but would make no practical sense, will only create one useless level of indirection.

Would Task be appropriate? Appropriate for what? It depends. If you explained some real goals someone or myself would probably advised you. But you specified some imaginary or maybe just poorly explained goal. Not any task. The idea of using one or another technique cannot be a goal. If you want to achieve something, you should better avoid mixing your questions with your ideas on how to achieve that. However, again, it depends.

To make the idea of invocation clear to you, please read my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

As to the custom task scheduler, it is rarely can be useful: https://msdn.microsoft.com/en-us/library/ee789351%28v=vs.110%29.aspx[^].

I really doubt that, even after your realize your real goals, it will help you. Again, it depends.

It really need deep understanding of the topic, to design your code properly using this approach.

—SA


Found a way!
Using LimitedConcurrencyLevelTaskScheduler class found on MSDN[^]!! :D


这篇关于如何在同一个线程中运行任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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