Aracılığıyla paylaş


Zaman uyumsuz dönüş türleri (C# ve Visual Basic)

Zaman uyumsuz yöntemleri üç olası dönüş türleri vardır: Task<TResult>, Taskve void.Visual Basic'te, void dönüş türü olarak yazılmış bir Sub yordam.Zaman uyumsuz yöntemleri hakkında daha fazla bilgi için bkz: Zaman uyumsuz zaman uyumsuz programlama ve beklemek (C# ve Visual Basic).

Dönüş türü her biri aşağıdaki bölümlerde incelenir ve konunun sonunda üç tür kullanan tam bir örnek bulabilirsiniz.

[!NOT]

Örneği çalıştırmak için Visual Studio 2012 sahip Visual Studio Express 2012 için Windows Masaüstü, veya bilgisayarınızda yüklü .NET Framework 4.5.

Bu konu, aşağıdaki bölümleri içermektedir.

  • Task(T) dönüş türü
  • Görev dönüş türü
  • Void dönüş türü
  • Tam Örnek
  • İlgili Konular

Task(T) dönüş türü

Task<TResult> Dönüş türü içeren bir zaman uyumsuz yöntemi için kullanılan bir dönmek (Visual Basic için) veya dönmek işlenen sahip türü (C#) deyimi TResult.

Aşağıdaki örnekte, TaskOfT_MethodAsync zaman uyumsuz yöntem bir tamsayı döndürür bir dönüş ifadesi içeriyor.Bu nedenle, yöntem bildirimi dönüş türü belirtmeniz gerekir Task(Of Integer) Visual Basic içinde veya Task<int> C# [NULL]'ta.

' TASK(OF T) EXAMPLE
Async Function TaskOfT_MethodAsync() As Task(Of Integer)

    ' The body of an async method is expected to contain an awaited 
    ' asynchronous call.
    ' Task.FromResult is a placeholder for actual work that returns a string.
    Dim today As String = Await Task.FromResult(Of String)(DateTime.Now.DayOfWeek.ToString())

    ' The method then can process the result in some way.
    Dim leisureHours As Integer
    If today.First() = "S" Then
        leisureHours = 16
    Else
        leisureHours = 5
    End If

    ' Because the return statement specifies an operand of type Integer, the 
    ' method must have a return type of Task(Of Integer). 
    Return leisureHours
End Function
// TASK<T> EXAMPLE
async Task<int> TaskOfT_MethodAsync()
{
    // The body of the method is expected to contain an awaited asynchronous
    // call.
    // Task.FromResult is a placeholder for actual work that returns a string.
    var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());

    // The method then can process the result in some way.
    int leisureHours;
    if (today.First() == 'S')
        leisureHours = 16;
    else
        leisureHours = 5;

    // Because the return statement specifies an operand of type int, the
    // method must have a return type of Task<int>.
    return leisureHours;
}

Zaman TaskOfT_MethodAsync olarak adlandırılan await deyim içinde await ifadeyi tamsayı değeri alır (değeri leisureHours) tarafından döndürülen görev depolanan TaskOfT_MethodAsync.Hakkında daha fazla bilgi için ifadeler bekler, bkz: Beklemek işleci (Visual Basic) veya beklemek (C# Reference).

Aşağıdaki kodu çağırır ve yöntem bekler TaskOfT_MethodAsync.Sonuç için atanmış result1 değişkeni.

' Call and await the Task(Of T)-returning async method in the same statement.
Dim result1 As Integer = Await TaskOfT_MethodAsync()
// Call and await the Task<T>-returning async method in the same statement.
int result1 = await TaskOfT_MethodAsync();

Nasıl çağrı ayırarak böyle daha iyi anlamak TaskOfT_MethodAsync uygulamadan Await veya await, aşağıdaki kodda gösterildiği gibi.Yöntemine çaðrý TaskOfT_MethodAsync hemen awaited döndürür, değilse bir Task(Of Integer) veya Task<int>, yöntemin bildiriminden beklediğiniz gibi.Görevin atandığı integerTask örnekte değişken.Çünkü integerTask olan bir Task<TResult>, onu içeren bir Result türünde özellik TResult.Bu durumda, TResult bir tamsayı türü temsil eder.Zaman Await veya await için uygulanan integerTask,'in içeriğine await deyimi değerlendirir Result özelliğini integerTask.Değer için atanan result2 değişkeni.

Uyarı notuUyarı

Result Engelleme özelliği özelliğidir.Kendi görev bitmeden önce onu erişmeye çalışırsanız, şu anda etkin olan iş parçacığı değeri kullanılabilir ve görev tamamlanıncaya kadar engellenir.Çoğu durumda, değeri kullanarak erişmek için kullanması Await veya await yerine özellik doğrudan erişim.

' Call and await in separate statements.
Dim integerTask As Task(Of Integer) = TaskOfT_MethodAsync()

' You can do other work that does not rely on resultTask before awaiting.
textBox1.Text &= String.Format("Application can continue working while the Task(Of T) runs. . . . " & vbCrLf)

Dim result2 As Integer = Await integerTask
// Call and await in separate statements.
Task<int> integerTask = TaskOfT_MethodAsync();

// You can do other work that does not rely on integerTask before awaiting.
textBox1.Text += String.Format("Application can continue working while the Task<T> runs. . . . \r\n");

int result2 = await integerTask;

Aşağıdaki kod görüntü deyimlerinde doğrulayın değerlerini result1 değişkeni, result2 değişken ve Result özelliği aynıdır.Unutmayın, Result engelleyen bir özelliktir ve kendi görev beklediğin önce erişilmesi gerekir.

' Display the values of the result1 variable, the result2 variable, and
' the resultTask.Result property.
textBox1.Text &= String.Format(vbCrLf & "Value of result1 variable:   {0}" & vbCrLf, result1)
textBox1.Text &= String.Format("Value of result2 variable:   {0}" & vbCrLf, result2)
textBox1.Text &= String.Format("Value of resultTask.Result:  {0}" & vbCrLf, integerTask.Result)
// Display the values of the result1 variable, the result2 variable, and
// the integerTask.Result property.
textBox1.Text += String.Format("\r\nValue of result1 variable:   {0}\r\n", result1);
textBox1.Text += String.Format("Value of result2 variable:   {0}\r\n", result2);
textBox1.Text += String.Format("Value of integerTask.Result: {0}\r\n", integerTask.Result);

Görev dönüş türü

Zaman uyumsuz yöntemleri veya bir dönüş ifadesi içeren olmayan bir işlenen genellikle çıktısı vermeyen bir dönüş ifadesi içeren dönüş türüne sahip Task.Bu tür yöntemler void döndüren yöntemleri (Sub Visual Basic'teki yordamlar) eşzamanlı çalışacak biçimde yazılmışsa.Kullanırsanız, bir Task için bir zaman uyumsuz yöntemi çağrılan yöntemin dönüş türü await işleç arayanın tamamlama zaman uyumsuz olarak adlandırılan yöntemin bitinceye kadar askıya almak için kullanabilirsiniz.

Aşağıdaki örnekte, zaman uyumsuz yöntem Task_MethodAsync bir dönüş ifadesi içermiyor.Bu nedenle, dönüş türü belirtmeniz Task sağlayan bir yöntem için Task_MethodAsync beklediğin için.Tanımını Task türü içermez bir Result dönüş değeri saklamak için özellik.

' TASK EXAMPLE
Async Function Task_MethodAsync() As Task

    ' The body of an async method is expected to contain an awaited 
    ' asynchronous call.
    ' Task.Delay is a placeholder for actual work.
    Await Task.Delay(2000)
    textBox1.Text &= String.Format(vbCrLf & "Sorry for the delay. . . ." & vbCrLf)

    ' This method has no return statement, so its return type is Task. 
End Function
// TASK EXAMPLE
async Task Task_MethodAsync()
{
    // The body of an async method is expected to contain an awaited 
    // asynchronous call.
    // Task.Delay is a placeholder for actual work.
    await Task.Delay(2000);
    // Task.Delay delays the following line by two seconds.
    textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");

    // This method has no return statement, so its return type is Task.  
}

Task_MethodAsyncçağrılan ve await benzer bir deyim, için bir zaman uyumlu arama ifadesi yerine await deyimini kullanarak beklediğin Sub veya void döndüren bir yöntem.Await işleci uygulama, bu durumda bir değer üretemiyor.

Aşağıdaki kodu çağırır ve yöntem bekler Task_MethodAsync.

' Call and await the Task-returning async method in the same statement.
Await Task_MethodAsync()
// Call and await the Task-returning async method in the same statement.
await Task_MethodAsync();

Önceki gibi Task<TResult> örnek, çağrı ayırmak Task_MethodAsync await işleç uygulamasından, aşağıdaki kod gösterir.Unutmayın ki bir Task sahip olmayan bir Result özelliği ve await işleç uygulandığında hiçbir değer üretilen bir Task.

Aşağıdaki kod arama ayıran Task_MethodAsync gelen görev bekleniyor, Task_MethodAsync döndürür.

' Call and await in separate statements.
Dim simpleTask As Task = Task_MethodAsync()

' You can do other work that does not rely on simpleTask before awaiting.
textBox1.Text &= String.Format(vbCrLf & "Application can continue working while the Task runs. . . ." & vbCrLf)

Await simpleTask
// Call and await in separate statements.
Task simpleTask = Task_MethodAsync();

// You can do other work that does not rely on simpleTask before awaiting.
textBox1.Text += String.Format("\r\nApplication can continue working while the Task runs. . . .\r\n");

await simpleTask;

Void dönüş türü

Void dönüş türü birincil kullanımı (Sub Visual Basic'teki yordamlar) olay işleyicileri bir void dönüş türü olduğu gerekli olur.Bir void dönüş void döndüren yöntemleri geçersiz kılmak için de kullanılabilir veya kategorilere ayrılabilir etkinlikleri gerçekleştiren yöntemleri için as "yangın ve Unut" Ancak, döndürmesi gereken bir Task Mümkünse, çünkü bir void döndüren zaman uyumsuz yöntem beklediğin.Herhangi bir arayan bir yöntemin sonuna kadar tamamlamak zaman uyumsuz olarak adlandırılan yöntemi için beklemeden devam edebilir ve arayan herhangi bir değer veya zaman uyumsuz yöntem oluşturduğu özel durumları bağımsız olması gerekir.

Void döndüren bir zaman uyumsuz yöntemini çağıran yönteminden atılan özel durumları yakalamak edemez ve böyle işlenmemiş özel durumları uygulamanızın başarısız olmasına neden olabilir.Döndüren bir zaman uyumsuz yöntem bir özel durum oluşursa bir Task veya Task<TResult>, özel durum döndürülen görev içinde saklanan ve görevi beklediğin, rethrown.Bu nedenle, bir özel durum oluşturabilir herhangi bir zaman uyumsuz yöntem dönüş türüne sahip olduğundan emin Task veya Task<TResult> ve yöntem çağrıları beklediğin.

Özel durumları yakalamak zaman uyumsuz yöntemleri hakkında daha fazla bilgi için bkz: try-catch (C# Reference) veya Try...Catch...Finally ifadesi (Visual Basic).

Aşağıdaki kod bir zaman uyumsuz olay işleyicisi tanımlar.

' SUB EXAMPLE
Async Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click

    textBox1.Clear()

    ' Start the process and await its completion. DriverAsync is a 
    ' Task-returning async method.
    Await DriverAsync()

    ' Say goodbye.
    textBox1.Text &= vbCrLf & "All done, exiting button-click event handler."
End Sub
// VOID EXAMPLE
private async void button1_Click(object sender, RoutedEventArgs e)
{
    textBox1.Clear();

    // Start the process and await its completion. DriverAsync is a 
    // Task-returning async method.
    await DriverAsync();

    // Say goodbye.
    textBox1.Text += "\r\nAll done, exiting button-click event handler.";
}

Tam Örnek

Aşağıdaki Windows Presentation Foundation (wpf) proje konudan kod örnekleri içerir.

Proje çalıştırmak için aşağıdaki adımları uygulayın:

  1. Visual &Studio'yu başlatın.

  2. Menü çubuğunda Dosya, Yeni, Proje'yi seçin.

    Yeni Proje iletişim kutusu açılır.

  3. İçinde yüklü, şablonları kategorisi seçin Visual Basic veya **Visual C#**ve sonra seçin Windows.Seçim wpf uygulaması proje türleri listesinde.

  4. Girin AsyncReturnTypes projenin adı ve sonra seçin Tamam düğmesi.

    Çözüm Gezgini'nde yeni proje görüntülenir.

  5. Visual Studio Kod Düzenleyicisi'nde seçin MainWindow.xaml sekme.

    Sekmesi görünür değilse, MainWindow.xaml içinde için kısayol menüsünü aç Çözüm Gezginive sonra seçin açık.

  6. İçinde xaml , MainWindow.xaml pencerenin kodu aşağıdaki kod ile değiştirin.

    <Window x:Class="MainWindow"
            xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button x:Name="button1" Content="Start" HorizontalAlignment="Left" Margin="214,28,0,0" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Center" FontWeight="Bold" FontFamily="Aharoni" Click="button1_Click"/>
            <TextBox x:Name="textBox1" Margin="0,80,0,0" TextWrapping="Wrap" FontFamily="Lucida Console"/>
    
        </Grid>
    </Window>
    
    <Window x:Class="AsyncReturnTypes.MainWindow"
            xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Button x:Name="button1" Content="Start" HorizontalAlignment="Left" Margin="214,28,0,0" VerticalAlignment="Top" Width="75" HorizontalContentAlignment="Center" FontWeight="Bold" FontFamily="Aharoni" Click="button1_Click"/>
            <TextBox x:Name="textBox1" Margin="0,80,0,0" TextWrapping="Wrap" FontFamily="Lucida Console"/>
    
        </Grid>
    </Window>
    

    Metin kutusu ve bir düğme içeren basit bir pencere görünür Tasarım MainWindow.xaml penceresi.

  7. İçinde Çözüm Gezgini, MainWindow.xaml.vb veya MainWindow.xaml.cs için kısayol menüsünü açın ve sonra seçin Görünüm kodu.

  8. MainWindow.xaml.vb veya MainWindow.xaml.cs kodu aşağıdaki kod ile değiştirin.

    Class MainWindow
    
        ' SUB EXAMPLE
        Async Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click
    
            textBox1.Clear()
    
            ' Start the process and await its completion. DriverAsync is a 
            ' Task-returning async method.
            Await DriverAsync()
    
            ' Say goodbye.
            textBox1.Text &= vbCrLf & "All done, exiting button-click event handler."
        End Sub
    
    
        Async Function DriverAsync() As Task
    
            ' Task(Of T) 
            ' Call and await the Task(Of T)-returning async method in the same statement.
            Dim result1 As Integer = Await TaskOfT_MethodAsync()
    
            ' Call and await in separate statements.
            Dim integerTask As Task(Of Integer) = TaskOfT_MethodAsync()
    
            ' You can do other work that does not rely on resultTask before awaiting.
            textBox1.Text &= String.Format("Application can continue working while the Task(Of T) runs. . . . " & vbCrLf)
    
            Dim result2 As Integer = Await integerTask
    
            ' Display the values of the result1 variable, the result2 variable, and
            ' the resultTask.Result property.
            textBox1.Text &= String.Format(vbCrLf & "Value of result1 variable:   {0}" & vbCrLf, result1)
            textBox1.Text &= String.Format("Value of result2 variable:   {0}" & vbCrLf, result2)
            textBox1.Text &= String.Format("Value of resultTask.Result:  {0}" & vbCrLf, integerTask.Result)
    
            ' Task 
            ' Call and await the Task-returning async method in the same statement.
            Await Task_MethodAsync()
    
            ' Call and await in separate statements.
            Dim simpleTask As Task = Task_MethodAsync()
    
            ' You can do other work that does not rely on simpleTask before awaiting.
            textBox1.Text &= String.Format(vbCrLf & "Application can continue working while the Task runs. . . ." & vbCrLf)
    
            Await simpleTask
        End Function
    
    
        ' TASK(OF T) EXAMPLE
        Async Function TaskOfT_MethodAsync() As Task(Of Integer)
    
            ' The body of an async method is expected to contain an awaited 
            ' asynchronous call.
            ' Task.FromResult is a placeholder for actual work that returns a string.
            Dim today As String = Await Task.FromResult(Of String)(DateTime.Now.DayOfWeek.ToString())
    
            ' The method then can process the result in some way.
            Dim leisureHours As Integer
            If today.First() = "S" Then
                leisureHours = 16
            Else
                leisureHours = 5
            End If
    
            ' Because the return statement specifies an operand of type Integer, the 
            ' method must have a return type of Task(Of Integer). 
            Return leisureHours
        End Function
    
    
        ' TASK EXAMPLE
        Async Function Task_MethodAsync() As Task
    
            ' The body of an async method is expected to contain an awaited 
            ' asynchronous call.
            ' Task.Delay is a placeholder for actual work.
            Await Task.Delay(2000)
            textBox1.Text &= String.Format(vbCrLf & "Sorry for the delay. . . ." & vbCrLf)
    
            ' This method has no return statement, so its return type is Task. 
        End Function
    
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace AsyncReturnTypes
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            // VOID EXAMPLE
            private async void button1_Click(object sender, RoutedEventArgs e)
            {
                textBox1.Clear();
    
                // Start the process and await its completion. DriverAsync is a 
                // Task-returning async method.
                await DriverAsync();
    
                // Say goodbye.
                textBox1.Text += "\r\nAll done, exiting button-click event handler.";
            }
    
            async Task DriverAsync()
            {
                // Task<T> 
                // Call and await the Task<T>-returning async method in the same statement.
                int result1 = await TaskOfT_MethodAsync();
    
                // Call and await in separate statements.
                Task<int> integerTask = TaskOfT_MethodAsync();
    
                // You can do other work that does not rely on integerTask before awaiting.
                textBox1.Text += String.Format("Application can continue working while the Task<T> runs. . . . \r\n");
    
                int result2 = await integerTask;
    
                // Display the values of the result1 variable, the result2 variable, and
                // the integerTask.Result property.
                textBox1.Text += String.Format("\r\nValue of result1 variable:   {0}\r\n", result1);
                textBox1.Text += String.Format("Value of result2 variable:   {0}\r\n", result2);
                textBox1.Text += String.Format("Value of integerTask.Result: {0}\r\n", integerTask.Result);
    
                // Task
                // Call and await the Task-returning async method in the same statement.
                await Task_MethodAsync();
    
                // Call and await in separate statements.
                Task simpleTask = Task_MethodAsync();
    
                // You can do other work that does not rely on simpleTask before awaiting.
                textBox1.Text += String.Format("\r\nApplication can continue working while the Task runs. . . .\r\n");
    
                await simpleTask;
            }
    
            // TASK<T> EXAMPLE
            async Task<int> TaskOfT_MethodAsync()
            {
                // The body of the method is expected to contain an awaited asynchronous
                // call.
                // Task.FromResult is a placeholder for actual work that returns a string.
                var today = await Task.FromResult<string>(DateTime.Now.DayOfWeek.ToString());
    
                // The method then can process the result in some way.
                int leisureHours;
                if (today.First() == 'S')
                    leisureHours = 16;
                else
                    leisureHours = 5;
    
                // Because the return statement specifies an operand of type int, the
                // method must have a return type of Task<int>.
                return leisureHours;
            }
    
    
            // TASK EXAMPLE
            async Task Task_MethodAsync()
            {
                // The body of an async method is expected to contain an awaited 
                // asynchronous call.
                // Task.Delay is a placeholder for actual work.
                await Task.Delay(2000);
                // Task.Delay delays the following line by two seconds.
                textBox1.Text += String.Format("\r\nSorry for the delay. . . .\r\n");
    
                // This method has no return statement, so its return type is Task.  
            }
        }
    }
    
  9. Seçim programını çalıştırın ve sonra seçmek için F5 tuşuna Start düğmesi.

    Aşağıdaki çıktıyı görüntülenmesi gerekir.

    Application can continue working while the Task<T> runs. . . . 
    
    Value of result1 variable:   5
    Value of result2 variable:   5
    Value of integerTask.Result: 5
    
    Sorry for the delay. . . .
    
    Application can continue working while the Task runs. . . .
    
    Sorry for the delay. . . .
    
    All done, exiting button-click event handler.
    

Ayrıca bkz.

Görevler

İzlenecek yol: zaman uyumsuz kullanarak Web'e erişme ve (C# ve Visual Basic) beklemek

İzlenecek Yol: Hata Ayıklayıcıyı Zaman Uyumsuz Yöntemlerle Kullanma

Başvuru

zaman uyumsuz (C# Reference)

Zaman uyumsuz (Visual Basic)

Beklemek işleci (Visual Basic)

beklemek (C# Reference)

FromResult<TResult>

Kavramlar

Denetim akışında zaman uyumsuz programlar (C# ve Visual Basic)