取消的BackgroundWorkerBackgroundWorker

由网友(八百逗比奔北波)分享简介:我有UI这显示长期运行的操作(从FTP下载一些文本文件)的状态。对于我的目的,我使用的BackgroundWorker,我无法取消操作。I have UI which displaying status of long-running operations (downloading some text files f...

我有UI这显示长期运行的操作(从FTP下载一些文本文件)的状态。对于我的目的,我使用的BackgroundWorker,我无法取消操作。

I have UI which displaying status of long-running operations (downloading some text files from ftp) . For my purposes I use backgroundworker and I can't cancel operation.

void worker_DoWork( object sender, DoWorkEventArgs e )
    {

        try
        {
            int rowIndex = (int)e.Argument;

            //begin UI update
            StartWaitingBar(rowIndex);
            //get provider id cell
            GridViewDataRowInfo row = _proivderGridView.Rows[rowIndex];
            GridViewCellInfo provIdCell = row.Cells[ "ProviderId" ];

            var providerData = GetProviderData(Convert.ToInt32( provIdCell.Value));
            var provider =  ProviderFactory.CreateProvider(providerData);
            provider.Synchronize();
            e.Result = rowIndex;

        }
        catch (Exception exception)
        {
           return;
        }
    }

和code为职工创造:

And code for worker creation:

           BackgroundWorker worker = new BackgroundWorker();
           worker.DoWork += worker_DoWork;
           worker.RunWorkerCompleted += worker_RunWorkerCompleted;
           worker.WorkerSupportsCancellation = true;
           worker.RunWorkerAsync(args.RowIndex);
          _syncWorkers.Add(providerId,worker);
           ...
            var worker = _syncWorkers[providerId];

            if(worker.IsBusy)
             {
                 worker.CancelAsync();
             }
            else
            {
                worker.RunWorkerAsync(args.RowIndex);
            }   

提供的解决方案here似乎不是为我工作怎么一回事,因为它适用于经常性操作(为其创建后台工作,我想)。我一定要使用线程(终止和联接),我的目的,因为我提供的可能性,用户取消长时间运行的操作?

Solution provided here seems not working for me beacuse it works for recurring operations (for which background worker is created, I suppose). Do I have to use threads(abort and join) for my purposes because I should provide possibilities for user to cancel long-running operation?

需要您的咨询。

在此先感谢。

推荐答案

您无法使用 Backgroundworker.CancelAsync()取消长时间运行的I / O操作。像rifnl应答,DoWork的必须检查 worker.CancellationPending ,并设置 e.Cancel

You cannot use Backgroundworker.CancelAsync() to cancel a long running I/O action. Like rifnl answered, the DoWork has to check worker.CancellationPending and set e.Cancel.

但你不应该使用 Thread.Abort的()无论是。它可能会破坏你的工艺。

But you shouldn't use Thread.Abort() either. It could destabilize your process.

您需要的解决方案必须来自 provider.Synchronize(); 不知何故

The solution you need has to come from provider.Synchronize(); somehow.

PS:和抓{返回; } 是可怕的。删除整个try / catch语句,让BGW处理异常。

PS: and catch { return; } is horrible. Remove the entire try/catch and let the Bgw handle exceptions.

阅读全文

相关推荐

最新文章