private void IncrementProgress(SynchronizationContext sync, SendingProgressForm form)
        {
            SendOrPostCallback c = (state) =>
            {
                form.Increment();
            };

            sync.Post(c, null);
        }
        private void StopProgressOnCancel(SynchronizationContext sync, SendingProgressForm form)
        {
            SendOrPostCallback c = (state) =>
            {
                MessageBox.Show("Cancelled");
                form.Close();
            };

            sync.Post(c, null);
        }
        private void CompleteProgress(SynchronizationContext sync, SendingProgressForm form)
        {
            SendOrPostCallback c = (state) =>
            {
                form.To100();
                MessageBox.Show("Completed");
                form.Close();
            };

            sync.Post(c, null);
        }
        private SendingProgressForm ShowProgressForm(SynchronizationContext sync, int itemsCount, CancellationTokenSource tokenSource)
        {
            SendingProgressForm form = new SendingProgressForm(itemsCount);
            SendOrPostCallback  c    = (state) =>
            {
                EventHandler cancelHandler = (o, args) =>
                {
                    tokenSource.Cancel();
                };
                form.SetCancelClickAction(cancelHandler);
                form.Show();
            };

            sync.Post(c, null);
            return(form);
        }
        private void buttonTransmit_Click(object sender, EventArgs e)
        {
            System.Runtime.GCSettings.LatencyMode = GCLatencyMode.LowLatency;

            if (activitiesTempStorage == null)
            {
                MessageBox.Show("There's nothing to transmit");
                return;
            }

            DisableFilterBox();
            DisableButtons();
            var sync = SynchronizationContext.Current;

            if (!this.sender.Authorized && e.GetType() != typeof(LoginPasswordEventArgs))
            {
                Task.Factory.StartNew(() =>
                {
                    LoginWithForm(sync);
                });
                return;
            }

            string login = string.Empty, password = string.Empty;

            if (!this.sender.Authorized)
            {
                login    = (e as LoginPasswordEventArgs).Login;
                password = (e as LoginPasswordEventArgs).Password;
                if (login == string.Empty || password == string.Empty)
                {
                    EnableButtons();
                    EnableFilterBox();
                    return;
                }
            }



            Task authorizationTask = new Task(() =>
            {
                if (!this.sender.Authorized) // after first 'if' data was obtained as EventArgs
                {
                    HttpStatusCode authorizationStatusCode;
                    bool success;
                    try
                    {
                        success = this.sender.Authorize(login, password, out authorizationStatusCode);
                    }
                    catch (WebException ex)
                    {
                        MessageBox.Show($"An error occured while authorization\n{ex.Message}");
                        return;
                    }

                    if (!success)
                    {
                        int authCode = (int)authorizationStatusCode;
                        MessageBox.Show($"Authorization failed. Code {authCode}: {authorizationStatusCode}");
                        EnableButtonsFromAnotherTask(sync);
                        EnableFilterBoxFromAnotherTask(sync);
                    }
                }
            });

            authorizationTask.Start();
            authorizationTask.Wait();

            if (!this.sender.Authorized)
            {
                return;
            }

            Task <List <Report> > splittingActivitiesListTask = new Task <List <Report> >(() =>
            {
                List <Report> r = new List <Report>();
                while (activitiesTempStorage.Count > 0)
                {
                    var a = activitiesTempStorage.Take(activitiesToSendAtOneTime).ToList();
                    r.Add(new Report()
                    {
                        Activities = a
                    });
                    activitiesTempStorage.RemoveRange(0, a.Count);
                }
                return(r);
            });

            splittingActivitiesListTask.Start();
            List <Report> reports = splittingActivitiesListTask.Result;



            var tokenSource  = new CancellationTokenSource();
            var cancellation = tokenSource.Token;
            SendingProgressForm sendingProgressForm = ShowProgressForm(sync, reports.Count, tokenSource);
            Task sendingTask = new Task((token) =>
            {
                CancellationToken cancellationToken = (CancellationToken)token;

                while (reports.Any())
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var report = reports.First();

                    HttpStatusCode sendStatusCode;
                    string result;
                    try
                    {
                        result = this.sender.SendActivities(report, out sendStatusCode);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"An error occured while sending activities\n{ex.Message}");
                        return;
                    }
                    int code = (int)sendStatusCode;

                    if (sendStatusCode == HttpStatusCode.Created)
                    {
                        reports.Remove(report);
                        IncrementProgress(sync, sendingProgressForm);
                    }
                }

                processor.MarkRegistriesAsProcessed(activitiesTempStorage.RegistriesIds);
            },
                                        cancellation, TaskCreationOptions.LongRunning);
            Task continuation = sendingTask.ContinueWith((obj) =>
            {
                if (cancellation.IsCancellationRequested)
                {
                    StopProgressOnCancel(sync, sendingProgressForm);
                }
                else
                {
                    CompleteProgress(sync, sendingProgressForm);
                }

                activitiesTempStorage = null;

                EnableFilterBoxFromAnotherTask(sync);
                EnableButtonsFromAnotherTask(sync);
                ClearDataFromAnotherTask(sync);
            });

            sendingTask.Start();
        }