Удаление асинхронной задачи в C#C#

Место общения программистов C#
Ответить
Anonymous
 Удаление асинхронной задачи в C#

Сообщение Anonymous »

Я изучаю программирование на C# и Android с помощью Xamarin.
Следуя нескольким руководствам, я создал простую программу, которая загружает изображение по URL-адресу с помощью асинхронного процесса.
Я хочу улучшить свой проект, добавив кнопка «Стоп», которая может удалить процесс.
Я следую этому руководству https://msdn.microsoft.com/enus/library ... .110).aspx
и добавил токен, но проблема возникла строка 90 моего кода.
Мой метод "GetByteArrayAsync("") не может принимать более одного параметра.

У вас есть предложения?

using Android.App;
using Android.Widget;
using Android.OS;
using System.IO;
using Android.Graphics;
using System.Threading.Tasks;
using System.Net.Http;
using System;
using System.Threading;
namespace App4
{
[Activity(Label = "App4", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
//Declare a Cancellation Token Source
CancellationTokenSource cts;

Button startbutton;
Button stopbutton;
TextView textView;
TextView textView1;
ImageView image;

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);

startbutton = FindViewById
(Resource.Id.startbutton);
stopbutton = FindViewById
(Resource.Id.stopbutton);
textView = FindViewById
(Resource.Id.textView);
image = FindViewById
(Resource.Id.image);
textView1 = FindViewById
(Resource.Id.textView1);
image.SetImageResource(Resource.Drawable.Icon);

//BASIC ASYNC START TASK
// click the startbutton to start the process
startbutton.Click += async (sender, e) =>
{
textView1.Text += " Loading...";

// Instantiate the CancellationTokenSource
cts = new CancellationTokenSource();

try
{
// **** GET ****
await DownloadImageAsync(cts.Token);
}
catch (System.OperationCanceledException)
{
textView1.Text += " Download deleted ";
}
catch (Exception)
{
textView1.Text += "Generic Error";
}

// ***Set the CancellationTokenSource to null when the download is complete.
cts = null;
};

//STOP BUTTON
stopbutton.Click += (sender,e) =>
{
if (cts != null)
{
cts.Cancel();
}
};
}

//ASYNC METHOD called by startbutton
public async Task DownloadImageAsync(CancellationToken ct)
{
var httpClient = new HttpClient();

// You might need to slow things down to have a chance to cancel.
await Task.Delay(500);

// byte[] imageBytes = await httpClient.GetByteArrayAsync("https://xamarin.com/content/images/page ... -h.jpg",ct);
byte[] imageBytes = await httpClient.GetByteArrayAsync("https://pbs.twimg.com/profile_images/60 ... 51.gif",ct);

//// THIS CODE STORE THE IMAGE IN THE LOCAL MEMORY OF THE APP////
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string localFilename = "image.jpg";
string localPath = System.IO.Path.Combine(documentsPath, localFilename);
File.WriteAllBytes(localPath, imageBytes);
textView1.Text = " Image downloaded.";

var localImage = new Java.IO.File(localPath);
if (localImage.Exists())
{
var teamBitmap = BitmapFactory.DecodeFile(localImage.AbsolutePath);
image.SetImageBitmap(teamBitmap);
}
///////////////////////////////////////////////////////////////////////////
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/439 ... in-c-sharp
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»