More .NET components

Asynchronous operations

Task-based Asynchronous Pattern (.NET 4.0 or later) #

.NET 4.0 introduced the Task-based Asynchronous Pattern (TAP). Rebex SFTP supports it as well, just reference the assemblies for .NET 4.0 from your project.

CSharp

// start async operation
Task<SftpItemCollection> t = sftp.GetListAsync();

// set continuation method
t.ContinueWith(GetListFinished);

VisualBasic

' start async operation
Dim t As Task(Of SftpItemCollection) = sftp.GetListAsync()

' set continuation method
t.ContinueWith(AddressOf GetListFinished)

Sample asynchronous continuation method:

CSharp

// this method is called when the async operation is completed
private void GetListFinished(Task<SftpItemCollection> t)
{
    // show error if any
    if (t.IsFaulted)
    {
        Console.WriteLine("An error occurred: {0}", t.Exception.ToString());
        return;
    }

    // show cancel notification
    if (t.IsCanceled)
    {
        Console.WriteLine("Operation was canceled.");
        return;
    }

    // get operation result
    SftpItemCollection list = t.Result;

    // show result
    Console.WriteLine("Listed {0} item(s).", list.Count);
}

VisualBasic

' this is called when the async operation is completed
Sub GetListFinished(ByVal t As Task(Of SftpItemCollection))
    ' show error if any
    If t.IsFaulted Then
        Console.WriteLine("An error occurred: {0}", t.Exception.ToString())
        Return
    End If

    ' show cancel notification
    If t.IsCanceled Then
        Console.WriteLine("Operation was canceled.")
        Return
    End If

    ' get operation result
    Dim list As SftpItemCollection = t.Result

    ' show result
    Console.WriteLine("Listed {0} item(s).", list.Count)
End Sub

'await' operator support (.NET 4.5 or later) #

.NET 4.5 introduced the 'await' operator, which makes writing asynchronous code more easy than ever before. Rebex SFTP supports it as well, just reference the assemblies for .NET 4.0 from your project.

CSharp

private async void GetList()
{
    try
    {
        // get list asynchronously
        SftpItemCollection list = await sftp.GetListAsync();

        // show result
        Console.WriteLine("Listed {0} item(s).", list.Count);
    }
    catch (SftpException ex)
    {
        if (ex.Status == SftpExceptionStatus.OperationAborted)
            Console.WriteLine("Operation was canceled.");
        else
            Console.WriteLine("An error occurred: {0}.", ex.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occurred: {0}", ex.ToString());
    }
}

VisualBasic

Public Async Sub GetList()
    Try
        ' get list asynchronously
        Dim list As SftpItemCollection = Await sftp.GetListAsync()

        ' show result
        Console.WriteLine("Listed {0} item(s).", list.Count)
    Catch ex As SftpException
        If ex.Status = SftpExceptionStatus.OperationAborted Then
            Console.WriteLine("Operation was canceled.")
        Else
            Console.WriteLine("An error occurred: {0}.", ex.Message)
        End If
    Catch ex As Exception
        Console.WriteLine("An error occurred: {0}", ex.ToString())
    End Try
End Sub

IAsyncResult pattern (Begin/End methods) #

The Asynchronous Programming Model (APM) pattern, also known as IAsyncResult (or Begin/End) pattern, was introduced in .NET 1.0. When you reference Rebex assemblies for .NET 2.0 in your project, this is the pattern you can use.

CSharp

// start async operation, specify callback
IAsyncResult ar = sftp.BeginGetList(GetListFinished, null);

VisualBasic

' start async operation, specify callback
Dim ar = sftp.BeginGetList(AddressOf GetListFinished, Nothing)

Sample asynchronous callback method:

CSharp

// this method is called when the Begin method is completed
private void GetListFinished(IAsyncResult ar)
{
    try
    {
        // get operation result
        SftpItemCollection list = sftp.EndGetList(ar);

        // show result
        Console.WriteLine("Listed {0} item(s).", list.Count);
    }
    catch (SftpException ex)
    {
        if (ex.Status == SftpExceptionStatus.OperationAborted)
            Console.WriteLine("Operation was canceled.");
        else
            Console.WriteLine("An error occurred: {0}.", ex.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("An error occurred: {0}", ex.ToString());
    }
}

VisualBasic

' this method is called when the Begin method is completed
Sub GetListFinished(ByVal ar As IAsyncResult)
    Try
        ' get operation result
        Dim list As SftpItemCollection = sftp.EndGetList(ar)

        ' show result
        Console.WriteLine("Listed {0} item(s).", list.Count)
    Catch ex As SftpException
        If ex.Status = SftpExceptionStatus.OperationAborted Then
            Console.WriteLine("Operation was canceled.")
        Else
            Console.WriteLine("An error occurred: {0}.", ex.Message)
        End If
    Catch ex As Exception
        Console.WriteLine("An error occurred: {0}", ex.ToString())
    End Try
End Sub

Using IAsyncResult in .NET 4.0 or later #

If you reference Rebex assemblies for .NET 4.0 or later from your project, but still wish to use the old-style IAsyncResult asynchronous pattern, include the Rebex.Legacy namespace.

By default, .NET 4.0 assemblies only present a Task-based pattern (TAP) asynchronous API. Rebex.Legacy namespace defines all the Begin/End methods as extension methods, making it possible to use to easily port old code to .NET 4.0 or higher.

CSharp

using Rebex.Legacy;

VisualBasic

#If LEGACY Then
Imports Rebex.Legacy
#End If

SynchronizationContext support for events #

When an asynchronous method on the Sftp object raises an event, it's dispatched using the synchronization context captured when the operation was started.

This greatly simplifies writing GUI applications (Windows Forms and WPF) because all the events are raised on the applications GUI thread, eliminating the need to explicitly marshal the calls using the Invoke method.

If you need to disable this functionality, set Sftp.Settings.RaiseEventsFromCurrentThread to true. This will cause all the events to be raised on the background operation's thread.