using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
namespace 异步编程
{
public delegate void UserDele(string msg);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//UserDele u = (string msg) => { WriteLog(msg); };
//Task.Run(() => { int i = 0; });
//Task t = Task.Run(async () => { return await Task.Run(() => { return 0; }); });
//Task.Run(() => Task.Run(() => { return 8; }));
}
private void button1_Click(object sender, EventArgs e)
{
MyStringDown my = new MyStringDown(new UserDele(WriteLog));
my.DoRun();
//Thread th = new Thread(my.DoRun);
//th.IsBackground = true;
//th.Start();
}
/// <summary>
/// 与MyStringDown中UserEvent事件匹配的方法,更新文本框。
/// </summary>
/// <param name="msg"></param>
public void WriteLog(string msg)
{
if (this.textBox1.InvokeRequired)
{
this.textBox1.Invoke(new UserDele(WriteLog), msg);
}
else
{
textBox1.Text = textBox1.Text + msg + "\r\n";
//this.textBox1.BeginInvoke(new UserDele(WriteLog), msg);
}
}
}
public class MyStringDown
{
public event UserDele UserEvent;
Stopwatch sw = new Stopwatch();
public MyStringDown(UserDele u)
{
UserEvent = u;
}
public void DoRun()
{
const int Count = 6000000;
sw.Start();
Task<int> t1 = CountCharactersAsync(1, "http://www.microsoft.com");
Task<int> t2 = CountCharactersAsync(2, "http://www.illustratedcsharp.com");
CountToLargeNumber(1, Count);
CountToLargeNumber(2, Count);
CountToLargeNumber(3, Count);
CountToLargeNumber(4, Count);
if (UserEvent != null)
{
UserEvent(string.Format("Chars in http://www.microsoft.com :{0}", t1.Result));
UserEvent(string.Format("Chars in http://www.illustratedcsharp.com :{0}", t2.Result));
}
else
{
throw new Exception("事件中的委托的方法列表为空");
}
}
private async Task<int> CountCharactersAsync(int id, string urlString)
{
//
WebClient web = new WebClient();
if (UserEvent != null)
{
UserEvent(string.Format("开始调用{0} : {1}ms", id, sw.Elapsed.TotalMilliseconds.ToString()));
string Msg =await web.DownloadStringTaskAsync(new Uri(urlString));
//Task<string> msg= Task.Run(() => {return web.DownloadStringTaskAsync(new Uri(urlString)); });
//await msg;
//if(UserEvent!=null)
UserEvent(string.Format("调用{0}完成 : {1}ms", id, sw.Elapsed.TotalMilliseconds.ToString()));
//MessageBox.Show("ssssssssssssssssssssss");
return Msg.Length;
//Func<int>U
}
else
{
throw new Exception("事件中的委托的方法列表为空");
}
}
private void CountToLargeNumber(int id, int value)
{
for (int i = 0; i < value; i++)
{
}
UserEvent(string.Format("第{0}次计数结束 : {1}ms", id, sw.Elapsed.TotalMilliseconds.ToString()));
}
}
}
代码如上所示,执行到UserEvent(string.Format("Chars in http://www.microsoft.com :{0}", t1.Result));时,界面整个直接卡死在那里了,想了很久也不知道是什么问题,如果在private void button1_Click(object sender, EventArgs e)中新开一个线程去执行my.DoRun()则不会出现这个现象,有大神可以解释一下吗?执行结果如图