Quantcast
Channel: Chilkat Forum - latest questions
Viewing all articles
Browse latest Browse all 1061

C# async await Task.Delay

$
0
0

We have a series of web service api endpoints that we use that will do some movements of files via FTP and other web requests. Since the underlying processes task advantage of many of the async Task processes when we call things like .Wait/Result we will end up blocking (which is by design). For the sleep state for our methods, we're using the Task.Delay (as shown in the sample below).

This is my first shot of using Chilkat in an async fashion, If there was a better way of doing this or if this is at least a sane approach?

Second part of the question, wrapping the Chilkat.Ftp2 in a using statement, I haven't seen samples that show this, but I would assume since it's implements IDisposible that using the using syntax would be the ideal approach. Any advantages/disadvantages of this in the scope of Chilkat?

public async Task DeleteRemoteFileAsync(string url, string path, string filename, string username, string password, CancellationToken ct)
{
  try
  {
    List<string> fileList = new List<string>();
    using (Chilkat.Ftp2 ftp = _GetFTPConnection(url, username, password))
    {
      if (!ftp.ChangeRemoteDir(path))
      {
        throw new Exception(ftp.LastErrorText);
      }
      Chilkat.Task task = ftp.DeleteRemoteFileAsync(filename);
      if (task == null)
      {
        throw new Exception(ftp.LastErrorText);
      }
      if (!task.Run())
      {
        throw new Exception(ftp.LastErrorText);
      }
      while (!task.Finished && !ct.IsCancellationRequested)
      {
        //Sleep 100 ms.
        await Task.Delay(100, ct);
      }
      ftp.Disconnect();
    }
  }
  catch (Exception ex)
  {
    throw ex;
  }
}

private Chilkat.Ftp2 _GetFTPConnection(string url, string username, string password)
{
  try
  {
    Chilkat.Ftp2 ftp = new Chilkat.Ftp2();
    if (!ftp.UnlockComponent(CHILKATFTPKEY))
    {
      throw new Exception(ftp.LastErrorText);
    }
    if (!ftp.IsUnlocked())
    {
      throw new Exception("Chilkat.Ftp2 is not unlocked");
    }

    ftp.Hostname = url;
    if (!ftp.ConnectOnly())
    {
      throw new Exception(ftp.LastErrorText);
    }
    ftp.Username = username;
    ftp.Password = password;
    if (!ftp.LoginAfterConnectOnly())
    {
      throw new Exception(ftp.LastErrorText);
    }
    return ftp;
  }
  catch (Exception ex)
  {
    ex.Data["Url"] = url;
    ex.Data["Username"] = username;
    throw ex;
  }
}

Viewing all articles
Browse latest Browse all 1061

Trending Articles