How to implement Stop/Cancel async operations in WinForms application when I can't pass token to async method?

81 Views Asked by At

I have asynchronious WinForms application that uses

  1. async/await event handlers of buttons
  2. objects with asynchronous method from another assembly that I can't modify.

I want

  1. to disable elements while operation is performing so I need to implement callback functions or just enable elements in Stop button
  2. and I want' to have button that stop performing operation.
private async void buttonCheckProxy_Click(object sender, EventArgs e)
{
    try
    {
        ProxySource src = (ProxySource)Enum.Parse(typeof(ProxySource), comboBoxSource.SelectedValue.ToString());
        Protocol prot = (Protocol)Enum.Parse(typeof(Protocol), comboBoxProtocol.SelectedValue.ToString());
        CheckType checkType = (CheckType)Enum.Parse(typeof(CheckType), comboBoxCheckType.SelectedValue.ToString());

        if (checkType == CheckType.WebRequest)
        {
            var cts = new CancellationTokenSource();

            await _proxyChecker.CheckAllWebRequestAsync(src, prot);
            MessageBox.Show("Completed");
        }
        else
        {
            await _proxyChecker.CheckAllWebBrowser(src, prot);
            MessageBox.Show("Completed");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

How I can make it for my purpose?

Before I used cancellation token but now I don't see how I can use it because I can't pass token to this function:

await _proxyChecker.CheckAllWebRequestAsync(src, prot);

Clarification: I want to kill the asynchronous CheckAllWebRequestAsync.

0

There are 0 best solutions below