C # .Net - How to undo BackgroundWorker by pulling data from WebService

I have the following code:

void ReferenceManager_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {

        // Get the raw data
        byte[] data = this.GetData(IvdSession.Instance.Company.Description, IvdSession.Instance.Company.Password);

        // Deserialize the list
        List<T> deseriaizedList = null;
        using (MemoryStream ms = new MemoryStream(data))
        {
            deseriaizedList = Serializer.Deserialize<List<T>>(ms);
        }

        // Convert the list to the Reference Interface
        List<IReference> referenceList = new List<IReference>();
        foreach (T entity in deseriaizedList)
        {
            IReference reference = (IReference)entity;
            referenceList.Add(reference);
        }

        e.Result = referenceList;

    }
    catch (WebException)
    {
        e.Result = null;
    }
}

Basically, the code calls the delegate for the WebService method. Unfortunately, the main reason I used the background worker was to stop freezing the user interface when loading data. I have a form that appears, saying please wait, click here to cancel.

When I click cancel, I call CancelAsync on the desktop background. Now that I am not looping, I don’t see a good way to check for cancellation. The only option I see is to have ...

byte[] m_CurrentData;

... DoWork (..), - m_CurrentData. , m_CurrentData .

?

+3
2

, -, this.GetData(...), . , -. , Abort() -, . CancelAsync(), , RunWorkerCompleted(). , , , _DoWork(), Result.Error Completed(). .

, CancelAsync() DoWork(). () , .

+3

MSDN DoWorkEventArgs , . BackgroundWorker CancellationPending, CancelAsync ( MSDN). , DoWork :

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Do not access the form BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = sender as BackgroundWorker;

    // Extract the argument.
    int arg = (int)e.Argument;

    // Start the time-consuming operation.
    e.Result = TimeConsumingOperation(bw, arg);

    // If the operation was canceled by the user, 
    // set the DoWorkEventArgs.Cancel property to true.
    if (bw.CancellationPending)
    {
        e.Cancel = true;
    }
}

?

+1

Source: https://habr.com/ru/post/1710096/


All Articles