閱讀英文版本

分享方式:


Timeout 類別

定義

包含會指定無限逾時間隔的常數。 此類別無法獲得繼承。

C#
public static class Timeout
C#
public sealed class Timeout
C#
[System.Runtime.InteropServices.ComVisible(true)]
public static class Timeout
繼承
Timeout
屬性

範例

下列範例顯示一段無限時間的執行緒進入睡眠狀態,並隨後被喚醒。

C#
using System;
using System.Security.Permissions;
using System.Threading;

class ThreadInterrupt
{
    static void Main()
    {
        StayAwake stayAwake = new StayAwake();
        Thread newThread = 
            new Thread(new ThreadStart(stayAwake.ThreadMethod));
        newThread.Start();

        // The following line causes an exception to be thrown 
        // in ThreadMethod if newThread is currently blocked
        // or becomes blocked in the future.
        newThread.Interrupt();
        Console.WriteLine("Main thread calls Interrupt on newThread.");

        // Tell newThread to go to sleep.
        stayAwake.SleepSwitch = true;

        // Wait for newThread to end.
        newThread.Join();
    }
}

class StayAwake
{
    bool sleepSwitch = false;

    public bool SleepSwitch
    {
        set{ sleepSwitch = value; }
    }

    public StayAwake(){}

    public void ThreadMethod()
    {
        Console.WriteLine("newThread is executing ThreadMethod.");
        while(!sleepSwitch)
        {
            // Use SpinWait instead of Sleep to demonstrate the 
            // effect of calling Interrupt on a running thread.
            Thread.SpinWait(10000000);
        }
        try
        {
            Console.WriteLine("newThread going to sleep.");

            // When newThread goes to sleep, it is immediately 
            // woken up by a ThreadInterruptedException.
            Thread.Sleep(Timeout.Infinite);
        }
        catch(ThreadInterruptedException e)
        {
            Console.WriteLine("newThread cannot go to sleep - " +
                "interrupted by main thread.");
        }
    }
}

備註

這個類別的成員可用來指定執行緒作業中的無限逾時間隔。 Infinite 是由接受整數 millisecondsTimeout 參數的方法使用,例如 Thread.Sleep(Int32)Thread.Join(Int32)ReaderWriterLock.AcquireReaderLock(Int32)InfiniteTimeSpan 是由接受 timeoutTimeSpan 別 參數的方法使用,例如 Thread.Sleep(TimeSpan)Thread.Join(TimeSpan)ReaderWriterLock.AcquireReaderLock(TimeSpan)

欄位

Infinite

用來為接受 Int32 參數之執行緒方法指定無限等候期間的常數。

InfiniteTimeSpan

用來為接受 TimeSpan 參數之方法指定無限等候期間的常數。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

執行緒安全性

此型別具備執行緒安全。

另請參閱