C#按下按钮即可在后台执行

时间:2018-11-20 00:45:37

标签: c# async-await httpwebrequest

有人可以解释我如何从此代码执行异步任务吗? 目前代码确实可以正常工作,但是我已经尝试使其异步了吗?因此,应用在执行时不会冻结,但不会成功。

public WebpageLocalScanner()
    {

        InitializeComponent();
        InitializeListView();

    }

internal string GetType(string ip, int port)
    {
        try
        {
            if (port == 1234 || port == 4321)
            {
                string urlAddress = string.Format("http://{0}", ip);
                string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
                if (text.Contains("<HTML>"))
                {
                    return "Webpage is here";
                }
            }
        }
        catch (Exception)
        {
        }
        return string.Empty;
    }


public void AddItem() {

            listView1.Items.Clear();

            int froms192 = Convert.ToInt32(tB1.Text);
            int froms168 = Convert.ToInt32(tB2.Text);
            int froms1a = Convert.ToInt32(tB3.Text);
            int froms1b = Convert.ToInt32(tB4.Text);
            int fromports = Convert.ToInt32(tBp1.Text);
            int toports = Convert.ToInt32(tBp2.Text);

            string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
            int FromPort = fromports;
            int ToPort = toports;

            int tos192 = Convert.ToInt32(tB5.Text);
            int tos168 = Convert.ToInt32(tB6.Text);
            int tos1a = Convert.ToInt32(tB7.Text);
            int tos1b = Convert.ToInt32(tB8.Text);

            string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;

            if (froms1a < tos1a || froms1b < tos1b)
            {

                for (int i = froms1b; i <= tos1b; i++)
                {

                    for (int u = froms1a; u <= tos1a; u++)
                    {   
                        for (int p = fromports; p <= toports; p++)
                        {
                        string GenIP = froms192 + "." + froms168 + "." + u + "." + i;


                        string result = GetType(GenIP, p);
                        if (result != null) {
                            string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                            var listViewItem = new ListViewItem(row);
                            listView1.Items.Add(listViewItem);
                        };


                        }
                    }
                }
            }

    }

private void InitializeListView()
    {
        // Set the view to show details.
        listView1.View = View.Details;
        // Allow the user to edit item text.
        listView1.LabelEdit = true;
        // Allow the user to rearrange columns.
        listView1.AllowColumnReorder = true;
        // Display check boxes.
        // listView1.CheckBoxes = true;
        // Select the item and subitems when selection is made.
        listView1.FullRowSelect = true;
        // Display grid lines.
        listView1.GridLines = true;
        // Sort the items in the list in ascending order.
        listView1.Sorting = SortOrder.Ascending;
        // Attach Subitems to the ListView
        listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
        listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);            
    }

private void button1_Click(object sender, EventArgs e)
    {
        AddItem();
    }

我真正挣扎的是理解如何将每个函数转换为返回值,并在调用后可以在后台使用。

无论我尝试什么,它都会丢失一些东西。 您能使我更清楚吗? 这样做只是扫描本地网络以找到其他PC上的Web服务器的当前IP。

但是255 ips需要花费一些时间,而应用程序却挂起了,不得不等到完成为止?

已应用答案代码:

public async void AddItem()
    {

        //listView1.Items.Clear();




        int froms192 = Convert.ToInt32(tB1.Text);
        int froms168 = Convert.ToInt32(tB2.Text);
        int froms1a = Convert.ToInt32(tB3.Text);
        int froms1b = Convert.ToInt32(tB4.Text);
        int fromports = Convert.ToInt32(tBp1.Text);
        int toports = Convert.ToInt32(tBp2.Text);

        string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
        int FromPort = fromports;
        int ToPort = toports;

        int tos192 = Convert.ToInt32(tB5.Text);
        int tos168 = Convert.ToInt32(tB6.Text);
        int tos1a = Convert.ToInt32(tB7.Text);
        int tos1b = Convert.ToInt32(tB8.Text);

        string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;

        if (froms1a < tos1a || froms1b < tos1b)
        {
            //var listViewItems = new List<ListViewItem>();
            await Task.Run(() =>
            {
                for (int i = froms1b; i <= tos1b; i++)
                {
                    List<string[]> rows = new List<string[]>();
                    for (int u = froms1a; u <= tos1a; u++)
                    {
                        for (int p = fromports; p <= toports; p++)
                        {
                            string GenIP = froms192 + "." + froms168 + "." + u + "." + i;

                            string result = GetProxyType(GenIP, p);
                            if (result != "")
                            {
                                string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                                var listViewItem = new ListViewItem(row);

                                if (listView1.InvokeRequired)
                                {
                                    listView1.Invoke(new MethodInvoker(delegate
                                    {


                                        listView1.Items.Add(listViewItem);

                                        //row.Checked = true;

                                    }));
                                }
                                else
                                {
                                    listView1.Items.Add(listViewItem);
                                    listViewItem.Checked = true;
                                } 
                                //string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                                //listViewItems.Add(row);
                                //listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());

                            };
                        }
                    }
                }

            });

        }

    }

    private async void button1_Click(object sender, EventArgs e)
    {

        AddItem();

    }

1 个答案:

答案 0 :(得分:1)

您将在需要异步运行的任何方法上使用async关键字。您在要在后台运行的代码上使用await。等待将控制权交还给UI,直到该代码完成。您仅对具有await的方法使用async,并且仅对返回Task的代码使用await。如果您有需要在后台运行的代码并且它没有返回Task,则可以将其包装在Task.Run中。

我认为这会起作用,但是我尚未对其进行测试。

public WebpageLocalScanner()
{

    InitializeComponent();
    InitializeListView();

}

internal string GetType(string ip, int port)
{
    try
    {
        if (port == 1234 || port == 4321)
        {
            string urlAddress = string.Format("http://{0}", ip);
            string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
            if (text.Contains("<HTML>"))
            {
                return "Webpage is here";
            }
        }
    }
    catch (Exception)
    {
    }
    return string.Empty;
}


public async void AddItem() {

        listView1.Items.Clear();

        int froms192 = Convert.ToInt32(tB1.Text);
        int froms168 = Convert.ToInt32(tB2.Text);
        int froms1a = Convert.ToInt32(tB3.Text);
        int froms1b = Convert.ToInt32(tB4.Text);
        int fromports = Convert.ToInt32(tBp1.Text);
        int toports = Convert.ToInt32(tBp2.Text);

        string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
        int FromPort = fromports;
        int ToPort = toports;

        int tos192 = Convert.ToInt32(tB5.Text);
        int tos168 = Convert.ToInt32(tB6.Text);
        int tos1a = Convert.ToInt32(tB7.Text);
        int tos1b = Convert.ToInt32(tB8.Text);

        string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;

        if (froms1a < tos1a || froms1b < tos1b)
        {
            var rows = new List<string[]>();
            await Task.Run(() => {
                for (int i = froms1b; i <= tos1b; i++)
                {
                    for (int u = froms1a; u <= tos1a; u++)
                    {   
                        for (int p = fromports; p <= toports; p++)
                        {
                            string GenIP = froms192 + "." + froms168 + "." + u + "." + i;

                            string result = GetType(GenIP, p);
                            if (result != null) {
                                string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                                rows.add(row);

                            };
                        }
                    }
                }
            });
            listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());
        }

}

private void InitializeListView()
{
    // Set the view to show details.
    listView1.View = View.Details;
    // Allow the user to edit item text.
    listView1.LabelEdit = true;
    // Allow the user to rearrange columns.
    listView1.AllowColumnReorder = true;
    // Display check boxes.
    // listView1.CheckBoxes = true;
    // Select the item and subitems when selection is made.
    listView1.FullRowSelect = true;
    // Display grid lines.
    listView1.GridLines = true;
    // Sort the items in the list in ascending order.
    listView1.Sorting = SortOrder.Ascending;
    // Attach Subitems to the ListView
    listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
    listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
    listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
    listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
    listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);            
}

private async void button1_Click(object sender, EventArgs e)
{
    AddItem();
}