C# 通过按下按钮在后台执行

C# By Pressing button do in background

谁能解释一下如何从这段代码中执行异步任务? 目前代码确实可以工作并且可以完成工作但是我试图让它异步?所以应用程序在执行时不会被冻结但没有成功。

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();
    }

我真正纠结的是理解如何将每个函数转换为 return 并且如果被调用可以在后台使用。

无论我尝试什么,它都会丢失一些东西。 你能帮我说得更清楚吗? 这只是简单地扫描本地网络以查找其他 pc 上的网络服务器的当前 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();

    }

您可以在任何需要异步 运行 的方法上使用 async 关键字。您对要在后台 运行 的代码使用 await 。 Await 将控制权交还给 UI 直到该代码完成。您仅在具有等待的方法上使用异步,并且仅在 return 是任务的代码上使用等待。如果您有代码需要在后台 运行 而它不是 return 任务,您可以将其包装在 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();
}