TimeoutException Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Исключение, которое возникает при истечении срока действия процесса или операции.
public ref class TimeoutException : Exception
public ref class TimeoutException : SystemException
public class TimeoutException : Exception
public class TimeoutException : SystemException
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class TimeoutException : SystemException
type TimeoutException = class
inherit Exception
type TimeoutException = class
inherit SystemException
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Serializable>]
type TimeoutException = class
inherit SystemException
Public Class TimeoutException
Inherits Exception
Public Class TimeoutException
Inherits SystemException
- Наследование
- Наследование
- Производный
- Атрибуты
Примеры
В следующем примере кода демонстрируется использование TimeoutException в сочетании с элементами System.IO.Ports.SerialPort класса.
// This example demonstrates the use of the TimeoutException
// exception in conjunction with the SerialPort class.
using System;
using System.IO.Ports;
class Sample
{
public static void Main()
{
string input;
try
{
// Set the COM1 serial port to speed = 4800 baud, parity = odd,
// data bits = 8, stop bits = 1.
SerialPort sp = new SerialPort("COM1",
4800, Parity.Odd, 8, StopBits.One);
// Timeout after 2 seconds.
sp.ReadTimeout = 2000;
sp.Open();
// Read until either the default newline termination string
// is detected or the read operation times out.
input = sp.ReadLine();
sp.Close();
// Echo the input.
Console.WriteLine(input);
}
// Only catch timeout exceptions.
catch (TimeoutException e)
{
Console.WriteLine(e);
}
}
}
/*
This example produces the following results:
(Data received at the serial port is echoed to the console if the
read operation completes successfully before the specified timeout period
expires. Otherwise, a timeout exception like the following is thrown.)
System.TimeoutException: The operation has timed-out.
at System.IO.Ports.SerialStream.ReadByte(Int32 timeout)
at System.IO.Ports.SerialPort.ReadOneChar(Int32 timeout)
at System.IO.Ports.SerialPort.ReadTo(String value)
at System.IO.Ports.SerialPort.ReadLine()
at Sample.Main()
*/
// This example demonstrates the use of the TimeoutException
// exception in conjunction with the SerialPort class.
open System
open System.IO.Ports
try
// Set the COM1 serial port to speed = 4800 baud, parity = odd,
// data bits = 8, stop bits = 1.
let sp = new SerialPort("COM1", 4800, Parity.Odd, 8, StopBits.One)
// Timeout after 2 seconds.
sp.ReadTimeout <- 2000
sp.Open()
// Read until either the default newline termination string
// is detected or the read operation times out.
let input = sp.ReadLine()
sp.Close()
// Echo the input.
printfn $"{input}"
// Only catch timeout exceptions.
with :? TimeoutException as e ->
printfn $"{e}"
(*
This example produces the following results:
(Data received at the serial port is echoed to the console if the
read operation completes successfully before the specified timeout period
expires. Otherwise, a timeout exception like the following is thrown.)
System.TimeoutException: The operation has timed-out.
at System.IO.Ports.SerialStream.ReadByte(Int32 timeout)
at System.IO.Ports.SerialPort.ReadOneChar(Int32 timeout)
at System.IO.Ports.SerialPort.ReadTo(String value)
at System.IO.Ports.SerialPort.ReadLine()
at Sample.main()
*)
' This example demonstrates the use of the TimeoutException
' exception in conjunction with the SerialPort class.
Imports System.IO.Ports
Class Sample
Public Shared Sub Main()
Dim input As String
Try
' Set the COM1 serial port to speed = 4800 baud, parity = odd,
' data bits = 8, stop bits = 1.
Dim sp As New SerialPort("COM1", 4800, Parity.Odd, 8, StopBits.One)
' Timeout after 2 seconds.
sp.ReadTimeout = 2000
sp.Open()
' Read until either the default newline termination string
' is detected or the read operation times out.
input = sp.ReadLine()
sp.Close()
' Echo the input.
Console.WriteLine(input)
' Only catch timeout exceptions.
Catch e As TimeoutException
Console.WriteLine(e)
End Try
End Sub
End Class
'
'This example produces the following results:
'
'(Data received at the serial port is echoed to the console if the
'read operation completes successfully before the specified timeout period
'expires. Otherwise, a timeout exception like the following is thrown.)
'
'System.TimeoutException: The operation has timed-out.
' at System.IO.Ports.SerialStream.ReadByte(Int32 timeout)
' at System.IO.Ports.SerialPort.ReadOneChar(Int32 timeout)
' at System.IO.Ports.SerialPort.ReadTo(String value)
' at System.IO.Ports.SerialPort.ReadLine()
' at Sample.Main()
'
Комментарии
Сведения о настройке интервала времени ожидания перед TimeoutException созданием исключения см. в документации по типу, время ожидания которого истекло. Сведения об обработке времени ожидания см. в документации по методу, вызвавшего исключение.
TimeoutException использует HRESULT, COR_E_TIMEOUT, который имеет значение 0x80131505.
Список начальных значений свойств для экземпляра TimeoutExceptionсм. в конструкторах TimeoutException.
Конструкторы
| Имя | Описание |
|---|---|
| TimeoutException() |
Инициализирует новый экземпляр класса TimeoutException. |
| TimeoutException(SerializationInfo, StreamingContext) |
Устаревшие..
Инициализирует новый экземпляр TimeoutException класса сериализованными данными. |
| TimeoutException(String, Exception) |
Инициализирует новый экземпляр TimeoutException класса с указанным сообщением об ошибке и внутренним исключением. |
| TimeoutException(String) |
Инициализирует новый экземпляр TimeoutException класса с указанным сообщением об ошибке. |
Свойства
| Имя | Описание |
|---|---|
| Data |
Возвращает коллекцию пар "ключ-значение", которые предоставляют дополнительные пользовательские сведения об исключении. (Унаследовано от Exception) |
| HelpLink |
Возвращает или задает ссылку на файл справки, связанный с этим исключением. (Унаследовано от Exception) |
| HResult |
Возвращает или задает HRESULT, закодированное числовое значение, назначенное определенному исключению. (Унаследовано от Exception) |
| InnerException |
Exception Возвращает экземпляр, вызвавшего текущее исключение. (Унаследовано от Exception) |
| Message |
Возвращает сообщение, описывающее текущее исключение. (Унаследовано от Exception) |
| Source |
Возвращает или задает имя приложения или объекта, вызывающего ошибку. (Унаследовано от Exception) |
| StackTrace |
Возвращает строковое представление непосредственных кадров в стеке вызовов. (Унаследовано от Exception) |
| TargetSite |
Возвращает метод, который вызывает текущее исключение. (Унаследовано от Exception) |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetBaseException() |
При переопределении в производном классе возвращает Exception первопричину одного или нескольких последующих исключений. (Унаследовано от Exception) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Устаревшие..
При переопределении в производном классе задает SerializationInfo с информацией об исключении. (Унаследовано от Exception) |
| GetType() |
Возвращает тип среды выполнения текущего экземпляра. (Унаследовано от Exception) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Создает и возвращает строковое представление текущего исключения. (Унаследовано от Exception) |
События
| Имя | Описание |
|---|---|
| SerializeObjectState |
Устаревшие..
Происходит при сериализации исключения для создания объекта состояния исключения, содержащего сериализованные данные об исключении. (Унаследовано от Exception) |