Question how to make cancel button to cancel or stop task async in my proxy checker code

Marlene E Coleman

New member
Joined
Apr 2, 2024
Messages
1
Programming Experience
1-3
C#:
namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        public async Task testProxy(string ip, int port)
        {
            bool OK = false;
            try
            {
                WebClient wc = new WebClient();
                wc.Proxy = new WebProxy(ip, port);
                await wc.DownloadStringTaskAsync(new Uri("[URL='http://google.com/ncr']Google[/URL]"));
                OK = true;
                addgood();
                richTextBox2.Text += ip + ":" + port + "\n";
            }
            catch { }
        }

        private void bunifuFlatButton1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "TXT Files | *.txt";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                proxy_list.Text = File.ReadAllText(@fileName);
                proxy_list.Refresh();
            }
        }

        private void start_Click(object sender, EventArgs e)  //start checker
        {
            if (proxy_list.Lines.Length < 1)
            {
                MessageBox.Show("Proxy list is Vide");
            }
            else
            {
                var asyncTasks = new Task[proxy_list.Lines.Length];
                for (int i = 0; i < proxy_list.Lines.Length; i++)
                {
                    var tab = proxy_list.Lines[I].Split(':');
                    asyncTasks[I] = testProxy(tab[0], int.Parse(tab[1]));
                }
                Task.WaitAll(asyncTasks);
            }
        }

     private void cancel_Click(object sender, EventArgs e) //stop checker
     {

         //cancel here 

     }
    }
}
 
Last edited by a moderator:
Please don't just dump your code without a full question or explanation of what you are trying to do, or what problem you have run into.
 
Anyway, all async methods (should) take a cancellation token. You should pass one into your various async method calls. In your cancel button handler, you can activate that token.

See:
 

Latest posts

Back
Top Bottom