相关疑难解决方法(0)

SwitchToThread/Thread.Yield vs. Thread.Sleep(0)vs. Thead.Sleep(1)

我正在尝试编写最终的"Yield"方法,以将当前时间片提供给其他线程.到目前为止,我发现有几种不同的方法可以使线程产生分配的时间片.我只是想确保我正确地解释它们,因为文档不是很清楚.因此,从我在stackoverflow,MSDN和各种博客文章中看到的内容,存在以下选项,它们都有不同的优点/缺点:

SwitchToThread[win32]/Thread.Yield[.NET 4 Beta 1]:产生同一处理器上的任何线程

  • 优势:大约快两倍 Thread.Sleep(0)
  • 缺点:仅产生同一处理器上的线程

Thread.Sleep(0):在任何处理器上产生任何具有相同或更高优先级的线程

  • 优点:比快 Thread.Sleep(1)
  • 缺点:仅产生相同或更高优先级的线程

Thread.Sleep(1):屈服于任何处理器上的任何线程

  • 优点:产生任何处理器上的任何线程
  • 缺点:最慢选项(Thread.Sleep(1)如果 不使用timeBeginPeriod/ timeEndPeriod[win32],通常会将线程暂停约15ms )

怎么样Thread.SpinWait?可以用它来产生线程的时间片吗?如果没有,它用于什么?

我还有其他一些我错过或错误解释的东西.如果你能纠正/增加我的理解,我将不胜感激.

这就是我的Yield方法到目前为止的样子:

public static class Thread
{
    [DllImport("kernel32.dll")]
    static extern bool SwitchToThread();

    [DllImport("winmm.dll")]
    internal static extern uint timeBeginPeriod(uint period);

    [DllImport("winmm.dll")]
    internal static extern uint timeEndPeriod(uint period);

    /// <summary>  yields time slice of current thread to specified target threads </summary>
    public static void YieldTo(ThreadYieldTarget threadYieldTarget)
    {
        switch (threadYieldTarget) { …
Run Code Online (Sandbox Code Playgroud)

.net concurrency multithreading

38
推荐指数
3
解决办法
1万
查看次数

ManualResetEventSlim建议等待时间

ManualResetEventSlim状态的MSDN文档

ManualResetEvent与预期等待时间非常短的情况相比,您可以使用此类获得更好的性能.

"很短"多久了?在什么时候使用内核对象的好处ManualResetEvent超过了实例化它的开销?

c# multithreading manualresetevent

22
推荐指数
1
解决办法
6249
查看次数

标签 统计

multithreading ×2

.net ×1

c# ×1

concurrency ×1

manualresetevent ×1