Task<TResult>.Result 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得這個 Task<TResult> 的結果值。
public:
property TResult Result { TResult get(); };
public TResult Result { get; }
member this.Result : 'Result
Public ReadOnly Property Result As TResult
屬性值
- TResult
這個 Task<TResult> 的結果值,其類型與工作的類型參數相同。
例外狀況
工作已取消。 InnerExceptions 集合包含 TaskCanceledException 物件。
-或- 在工作執行期間擲回例外狀況。 InnerExceptions 集合包含例外狀況的相關資訊。
範例
下列範例是命令列公用程式,會計算每個目錄中名稱傳遞為命令列引數之檔案中的位元組數目。 如果目錄包含檔案,它會執行 Lambda 運算式,以具現化 FileStream 目錄中每個檔案的物件,並擷取其 FileStream.Length 屬性的值。 如果目錄不包含任何檔案,它只會呼叫 FromResult 方法來建立 Task<TResult>.Result 屬性為零 (0) 的工作。 當工作完成時,可從 屬性取得所有目錄檔案 Result 中的位元組總數。
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1) {
List<Task<long>> tasks = new List<Task<long>>();
for (int ctr = 1; ctr < args.Length; ctr++)
tasks.Add(GetFileLengthsAsync(args[ctr]));
try {
Task.WaitAll(tasks.ToArray());
}
// Ignore exceptions here.
catch (AggregateException) {}
for (int ctr = 0 ; ctr < tasks.Count; ctr++) {
if (tasks[ctr].Status == TaskStatus.Faulted)
Console.WriteLine("{0} does not exist", args[ctr + 1]);
else
Console.WriteLine("{0:N0} bytes in files in '{1}'",
tasks[ctr].Result, args[ctr + 1]);
}
}
else {
Console.WriteLine("Syntax error: Include one or more file paths.");
}
}
private static Task<long> GetFileLengthsAsync(string filePath)
{
if (! Directory.Exists(filePath)) {
return Task.FromException<long>(
new DirectoryNotFoundException("Invalid directory name."));
}
else {
string[] files = Directory.GetFiles(filePath);
if (files.Length == 0)
return Task.FromResult(0L);
else
return Task.Run( () => { long total = 0;
Parallel.ForEach(files, (fileName) => {
var fs = new FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite,
256, true);
long length = fs.Length;
Interlocked.Add(ref total, length);
fs.Close(); } );
return total;
} );
}
}
}
// When launched with the following command line arguments:
// subdir . newsubdir
// the example displays output like the following:
// 0 bytes in files in 'subdir'
// 2,059 bytes in files in '.'
// newsubdir does not exist
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Module Example
Public Sub Main()
Dim args() As String = Environment.GetCommandLineArgs()
If args.Length > 1 Then
Dim tasks As New List(Of Task(Of Long))
For ctr = 1 To args.Length - 1
tasks.Add(GetFileLengthsAsync(args(ctr)))
Next
Try
Task.WaitAll(tasks.ToArray())
' Ignore exceptions here.
Catch e As AggregateException
End Try
For ctr As Integer = 0 To tasks.Count - 1
If tasks(ctr).Status = TaskStatus.Faulted Then
Console.WriteLine("{0} does not exist", args(ctr + 1))
Else
Console.WriteLine("{0:N0} bytes in files in '{1}'",
tasks(ctr).Result, args(ctr + 1))
End If
Next
Else
Console.WriteLine("Syntax error: Include one or more file paths.")
End If
End Sub
Private Function GetFileLengthsAsync(filePath As String) As Task(Of Long)
If Not Directory.Exists(filePath) Then
Return Task.FromException(Of Long)(
New DirectoryNotFoundException("Invalid directory name."))
Else
Dim files As String() = Directory.GetFiles(filePath)
If files.Length = 0 Then
Return Task.FromResult(0L)
Else
Return Task.Run( Function()
Dim total As Long = 0
Dim lockObj As New Object
Parallel.ForEach(files, Sub(fileName)
Dim fs As New FileStream(fileName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite,
256, True)
Dim length As Long = fs.Length
Interlocked.Add(total, length)
fs.Close()
End Sub)
Return total
End Function )
End If
End If
End Function
End Module
' When launched with the following command line arguments:
' subdir . newsubdir
' the example displays output like the following:
' 0 bytes in files in 'subdir'
' 2,059 bytes in files in '.'
' newsubdir does not exist
備註
存取屬性的 get 存取子會封鎖呼叫執行緒,直到非同步作業完成為止;它相當於呼叫 Wait 方法。
一旦作業的結果可供使用,就會儲存該作業,並在屬性的後續呼叫 Result 時立即傳回。 請注意,如果在工作作業期間發生例外狀況,或工作已取消, Result 則 屬性不會傳回值。 相反地,嘗試存取屬性值會 AggregateException 擲回例外狀況。