言語いろいろやってると、毎回忘れるやーつ。
そして公開するの忘れてたw
Form1.cs
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{ public partial class Form1 : Form { // 変数を定義 private static HttpClient client = new HttpClient(); private static CancellationTokenSource tokenSource; public Form1() { InitializeComponent(); } // 非同期処理を実行するボタン private async void button3_Click(object sender, EventArgs e) { // トークンを新しく発行 tokenSource = new CancellationTokenSource(); var cancelToken = tokenSource.Token; // 非同期処理を呼び出す var a = await AsyncTest(cancelToken); // 非同期処理の結果を表示 MessageBox.Show(a.ToString(), "button3_Click End"); } // 非同期処理をボタンイベントに全てを記述する場合 private void button4_Click(object sender, EventArgs e) { var task = Task.Run(async () => { await Task.Delay(1000); MessageBox.Show("1", "button4_Click End"); }); } // キャンセルボタン private void button5_Click(object sender, EventArgs e) { // キャンセルを送信 tokenSource.Cancel(); } // 非同期処理 public async Task AsyncTest(CancellationToken cancelToken) { // 時間のかかる処理を実行 for (int i = 0; i 5; i++) { // 1000ミリ秒待機 await Task.Delay(1000); if (cancelToken.IsCancellationRequested) { // キャンセル終了 return 0; } } // 正常終了 return 1; } public async Task AsyncHttpTest() { // HTTP通信でHTMLの内容を取得 var response = await client.GetAsync("http://www.itcowork.co.jp/"); // 文字型に変換 var text = await response.Content.ReadAsStringAsync(); return text.ToString(); } }
}