fhfhrfhf 2016-09-02 15:16 采纳率: 0%
浏览 941

关于async和await的问题

图片说明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()则不会出现这个现象,有大神可以解释一下吗?执行结果如图

  • 写回答

1条回答 默认 最新

  • dabocaiqq 2017-02-08 20:27
    关注

    代码比较多可以简化的,参考下相关的例子

    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题