Mega API Client: Cancellationtoken at Downloadfileasync

Asked

Viewed 36 times

0

I started using a MEGA file cloud API where I can upload and download the files from the cloud. Nuget Package here, I’m doing fine:

using CG.Web.MegaApiClient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsMegaDownload
{
    public partial class Form1 : Form
    {
        private double bytesTotal;
        private long bytesT;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            
            var client = new MegaApiClient();
            client.Login("Meu Email", "Senha");

            //INode principal
            IEnumerable<INode> home = client.GetNodes();
            List<INode> homeContent = home.Where(n => n.Type == NodeType.Directory).ToList();
            INode home_jogos = homeContent.FirstOrDefault(f => f.Name == "Jogos");
            
            //Node da home\\pasta
            IEnumerable<INode> jogos = client.GetNodes(home_jogos);
            List<INode> allfiles = jogos.Where(n => n.Type == NodeType.File).ToList();
            INode myFile = allfiles.FirstOrDefault(f => f.Name == "sparkle_setup.exe");

            bytesTotal = double.Parse(myFile.Size.ToString()) / 1024 / 1024;
            bytesT = myFile.Size;

            var progress = new Progress<double>();
            progress.ProgressChanged += new EventHandler<double>(progressChanged);

            Thread progressCompleted = new Thread(new ThreadStart(progressComplete));
            progressCompleted.Start();

            client.DownloadFileAsync(myFile, "sparkle_setup.exe", progress);
            
        }

        private void progressComplete()
        {
            bool completed = false;
            while (!completed)
            {
                if (File.Exists("sparkle_setup.exe"))
                {
                    if(new FileInfo("sparkle_setup.exe").Length == bytesT)
                    {
                        completed = true;
                    }
                }
                
            }
        }

        private void progressChanged(object sender, double e)
        {
            double bytesIn = double.Parse(new FileInfo("sparkle_setup.exe").Length.ToString()) / 1024 / 1024;
            

            progressBar1.Value = Convert.ToInt32(e);
            label1.Text = progressBar1.Value.ToString() + "% | " + bytesIn.ToString("F2") + "/" + bytesTotal.ToString("F2") + " MB";
        }
    }
}

In JIT:

inserir a descrição da imagem aqui

First start with logging in, then create inodes that are the path to the cloud folders until you get what you need. Like Megaapiclient, the class is not similar to Webclient about the events I decided to do manually. Method Downloadfileasync.

public Task DownloadFileAsync(INode node, string outputFile, IProgress<double> progress = null, CancellationToken? cancellationToken = default(CancellationToken? ))

This is the structure of the method, I put the Inode of the file I had (I didn’t even remember it), the output path and a Progress item that makes the progressiChanged. I just don’t get this CancellationToken? cancellationToken = default(CancellationToken? ). Does he have anything to do with whether or not progress has been completed? I didn’t do anything about this parameter instead I created a Downloadcompleted thread.

1 answer

1


A CancelationToken is an object used to notify a thread that the code that started the process wants to cancel.

As a thread is an asynchronous process, the code that starts "loses" control over it, and is waiting to be notified that the process of thread finished, what we call callback.

Now imagine that for some reason if you want to cancel this, or because you don’t need it anymore, because it’s taking too long (timeout) or any other reason, this would not be possible because the process is asynchronous, so the CancelationToken is a "link" so to speak with the process that started the thread and she, and can use this to notify that she wants the process to be canceled.

At that point, the thread should be able to handle it. In your example DownloadFileAsync, then probably the download will be canceled.

To do this, create an object, do not pass the "default", like this:

CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;

And to cancel, use the method Cancel(): source.Cancel();

You can read more about here: https://docs.microsoft.com/pt-br/dotnet/api/system.threading.cancellationtoken

Browser other questions tagged

You are not signed in. Login or sign up in order to post.