Mono Touch文件下载

本文介绍如何在Mono Touch应用中使用await和async关键字进行文件下载操作,涉及WriteAsync和Scale等相关技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

贴主要代码:

using System;
using System.IO;
using System.Drawing;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;

using MonoTouch.CoreGraphics;
using MonoTouch.CoreImage;

using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace AsyncDownloadImage
{
	public partial class AsyncDownloadImageViewController : UIViewController
	{
		int clickNumber = 0;
		WebClient webClient;
		public AsyncDownloadImageViewController () : base ("AsyncDownloadImageViewController", null)
		{
		}

		public override void DidReceiveMemoryWarning ()
		{
			// Releases the view if it doesn't have a superview.
			base.DidReceiveMemoryWarning ();

			// Release any cached data, images, etc that aren't in use.
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			this.clickButton.TouchUpInside += (sender, e) => {
				clickNumber++;
				this.clickButton.SetTitle( "Click Me:" + clickNumber, UIControlState.Normal);
			};

			this.downloadButton.TouchUpInside += downloadAsync;

			this.downloadProgress.Progress = 0.0f;

		}

		async void downloadAsync(object sender, System.EventArgs ea)
		{
			webClient = new WebClient ();
			//An large image url
			var url = new Uri ("http://photojournal.jpl.nasa.gov/jpeg/PIA15416.jpg");
			byte[] bytes = null;


			webClient.DownloadProgressChanged += HandleDownloadProgressChanged;

			this.downloadButton.SetTitle ("Cancel",UIControlState.Normal);
			this.downloadButton.TouchUpInside -= downloadAsync;
			this.downloadButton.TouchUpInside += cancelDownload;
			infoLabel.Text = "Downloading...";

			//Start download data using DownloadDataTaskAsync
			try{
				bytes = await webClient.DownloadDataTaskAsync(url);
			}
			catch(TaskCanceledException){
				Console.WriteLine ("Task Canceled!");
				return;
			}
			catch(Exception e) {
				Console.WriteLine (e.ToString());
				return;
			}
			string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);	
			string localFilename = "downloaded.png";
 			string localPath = Path.Combine (documentsPath, localFilename);
			infoLabel.Text = "Download Complete";

			//Save the image using writeAsync
			FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate);
			await fs.WriteAsync (bytes, 0, bytes.Length);

			Console.WriteLine("localPath:"+localPath);


			//Resizing image is time costing, using async to avoid blocking the UI thread
			UIImage image = null;
			SizeF imageViewSize = imageView.Frame.Size;
	
			infoLabel.Text = "Resizing Image...";
			await Task.Run( () => { image = UIImage.FromFile(localPath).Scale(imageViewSize); } );
			Console.WriteLine ("Loaded!");

			imageView.Image = image;

			infoLabel.Text = "Click Dowload button to download the image";


			this.downloadButton.TouchUpInside -= cancelDownload;
			this.downloadButton.TouchUpInside += downloadAsync;
			this.downloadButton.SetTitle ("Download", UIControlState.Normal);
			this.downloadProgress.Progress = 0.0f;
		}



		void HandleDownloadProgressChanged (object sender, DownloadProgressChangedEventArgs e)
		{
			this.downloadProgress.Progress = e.ProgressPercentage / 100.0f;
		}

		void cancelDownload(object sender, System.EventArgs ea)
		{
			Console.WriteLine ("Cancel clicked!");
			if(webClient!=null)
				webClient.CancelAsync ();

			webClient.DownloadProgressChanged -= HandleDownloadProgressChanged;

			this.downloadButton.TouchUpInside -= cancelDownload;
			this.downloadButton.TouchUpInside += downloadAsync;
			this.downloadButton.SetTitle ("Download", UIControlState.Normal);
			this.downloadProgress.Progress = 0.0f;

			new UIAlertView ("Canceled"
			                 , "Download has been canceled."
			                 , null
			                 , "OK"
			                 , null).Show();
			infoLabel.Text = "Click Dowload button to download the image";
		}


		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			// Return true for supported orientations
			return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
		}
	}
}


### 使用 Mono 开发工具 Mono 开发工具是一套用于构建、调试和部署基于 .NET 的应用程序的开源解决方案。它不仅可以在 Windows 平台上运行,还能够支持 Linux 和 macOS 等其他操作系统。以下是关于如何使用 Mono 开发工具的一些关键点: #### 1. 安装 Mono 开发环境 为了开始使用 Mono 开发工具,首先需要在其支持的操作系统上安装 Mono 环境。 - **在 Ubuntu 或 Debian 上安装** 可以通过 `apt` 包管理器完成安装过程: ```bash sudo apt update && sudo apt upgrade sudo apt install mono-complete ``` - **在 CentOS 或 RHEL 上安装** 对于 Red Hat 类型的发行版,可以使用 `yum` 来安装 Mono: ```bash sudo yum install epel-release sudo yum install mono-complete ``` 这些命令会下载并安装完整的 Mono 套件,其中包括编译器、库文件以及必要的开发工具[^3]。 #### 2. 创建第一个 Mono 应用程序 一旦安装完毕,就可以编写简单的 C# 程序并通过 Mono 编译执行它们。 - **创建源代码文件** 首先,在终端中导航至一个目录,并创建一个新的 `.cs` 文件作为项目的起点: ```bash mkdir ~/monoproject && cd ~/monoproject touch HelloWorld.cs ``` 接下来编辑该文件的内容如下所示: ```csharp using System; namespace HelloApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello, world!"); } } } ``` - **编译与运行** 利用 Mono 提供的 C# 编译器 (mcs),将上述代码转换成可执行的应用程序: ```bash mcs -out:HelloWorld.exe HelloWorld.cs mono HelloWorld.exe ``` 如果一切正常,则会在控制台看到消息 “Hello, world!” 输出[^4]。 #### 3. 跨平台 WinForms 应用开发 除了基本的控制台应用外,开发者也可以借助 Mono 实现图形界面程序(GUI)。例如移植现有的 Windows Forms (.NET Framework GUI API) 至 Linux 中运行。 - **设置依赖项** 在某些情况下可能还需要额外安装 GTK+ 绑定以便更好地兼容 UI 渲染需求: ```bash sudo apt-get install libgtk2.0-dev ``` - **示例项目结构** 下面是一个简单例子展示如何利用 Mono 构建跨平台窗体应用: ```csharp using System; using System.Windows.Forms; public class MyForm : Form { private Button button; public MyForm() { this.Text = "Cross Platform App"; this.button = new Button(); this.button.Text = "Click Me!"; this.Controls.Add(button); } [STAThread] public static void Main() { Application.Run(new MyForm()); } } ``` 此脚本定义了一个带有按钮的小窗口;当点击按钮时不会触发任何动作,但它足以演示基础功能[^5]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值