使用委托创建表单但从未完成的异步方法

时间:2017-11-01 22:38:59

标签: c# asynchronous async-await

我有一个似乎永远无法完成的c#异步方法。它通过委托调用并创建一个表单。如果我删除委托或表单创建它工作正常。任何见解将不胜感激!代码如下:

public delegate Task<bool> TaskDel();

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        button1.Tag = (TaskDel)taskAsync; 
    }

    private async void button1_Click(object sender, EventArgs e)
    {
        // if I don't use a delegate here there is no problem.
        await Task.Run(() => ((sender as Button).Tag as TaskDel)());
    }

    public async Task<bool> taskAsync()
    {
        await new HttpClient().GetStringAsync(URL);
        Form form = new Form(); // if I remove this line method works.
        await new HttpClient().GetStringAsync(URL);
        return true; // as is, never reaches this line
    }
}

1 个答案:

答案 0 :(得分:5)

  1. 在异步任务中,我认为不应该执行UI操作。异步任务通常用于资源匮乏,长时间运行的过程,例如轮询数据的URL(如此处所做),或长度计算,反序列化数据文件等。您无法直接与调用表单上的任何UI控件交互

  2. 不需要使用委托。你可以直接打电话:

    private async void button1_Click(Object sender, EventArgs e)
    {
        await new HttpClient().GetStringAsync(URL);
        Form form = new Form();
    }