C#如何正确停止后台工作? [英] C# how to stop backgroundworker correctly?

查看:91
本文介绍了C#如何正确停止后台工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上找到了以下代码。这个一个简单的代码示例,它是如何工作的BackgroundWorker,它运行良好。 
我需要代码才能正确中止(停止)BackgroundWorker。
我想知道它是如何工作的。非常感谢。





  private   void  BackgroundWorker_DoWork( object  sender,DoWorkEventArgs e)
{
byte [] buffer;
byte [] oldBuffer;
int bytesRead;
int oldBytesRead;
大小;
long totalBytesRead = 0 ;

使用(Stream stream = File.OpenRead(( string )e。参数))
使用(HashAlgorithm hashAlgorithm = MD5.Create())
{
size = stream.Length;

buffer = new byte [ 4096 ];

bytesRead = stream.Read(buffer, 0 ,buffer.Length);
totalBytesRead + = bytesRead;

do
{
oldBytesRead = bytesRead;
oldBuffer = buffer;

buffer = new byte [ 4096 ];
bytesRead = stream.Read(buffer, 0 ,buffer.Length);

totalBytesRead + = bytesRead;

if (bytesRead == 0
{
hashAlgorithm.TransformFinalBlock(oldBuffer, 0 ,oldBytesRead);
}
else
{
hashAlgorithm.TransformBlock(oldBuffer, 0 ,oldBytesRead,oldBuffer, 0 );
}

BackgroundWorker.ReportProgress(( int )(( double )totalBytesRead * 100 / size));
} while (bytesRead!= 0 );

e.Result = hashAlgorithm.Hash;
}
}

私有 void BackgroundWorker_RunWorkerCompleted( object sender,RunWorkerCompletedEventArgs e)
{
StringBuilder sb;

sb = new StringBuilder();

ProgressPercentage.Visible = false ;
ProgressBar.Visible = false ;
StatusText.Text = ;

foreach byte b in byte [])e.Result)
{
sb.AppendFormat( {0:X2},b);
}
HashTextbox.Text = sb.ToString();

}

private void BackgroundWorker_ProgressChanged(< span class =code-keyword> object
sender,ProgressChangedEventArgs e)
{
ProgressBar.Value = e.ProgressPercentage;
ProgressPercentage.Text = e.ProgressPercentage + ;
}





我的尝试:



if(backgroundWorker1.IsBusy == true)

{



backgroundWorker1.CancelAsync();

while(backgroundWorker1.IsBusy == true)

{

backgroundWorker1.CancelAsync();

}



backgroundWorker1.Dispose();



}



backgroundWorker1.RunWorkerAsync();

解决方案

当你尝试代码时发生了什么?有错误吗?它没有做你预期的事情吗?



您需要在MSDN上学习文档和示例:[ ^ ]。



将BackgroundWorker的属性'WorkerSupportsCancellation设置为true,并在'DoWork方法中检查循环内的'CancellationPending属性;如果'CancellationPending'为true,则将e.Cancel EventArgs属性设置为'true。



调用'CancelAsynch来停止工人。 MSDN上的示例演示了您需要了解的所有内容。



复制您在网络上找到的代码,而不是实际学习文档,或搜索CodeProject或StackOverFlow的示例或提示,是确保你没有学习如何编程的好方法。



想想你开始知道自己实际上有多好 掌握 .NET和C#语言的力量,你将如何对自己说:好吧,努力工作是值得的。 :)

This code below I found on the Internet. This is a simple example of code how works BackgroundWorker, and it works well.
I need the code to Abort (stop) BackgroundWorker correctly. 
I want to know how it works. Thanks a lot.



private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            byte[] buffer;
            byte[] oldBuffer;
            int bytesRead;
            int oldBytesRead;
            long size;
            long totalBytesRead = 0;
          
            using (Stream stream = File.OpenRead((string) e.Argument))
            using (HashAlgorithm hashAlgorithm = MD5.Create())
            {
                size = stream.Length;

                buffer = new byte[4096];

                bytesRead = stream.Read(buffer, 0, buffer.Length);
                totalBytesRead += bytesRead;

                do
                {
                    oldBytesRead = bytesRead;
                    oldBuffer = buffer;

                    buffer = new byte[4096];
                    bytesRead = stream.Read(buffer, 0, buffer.Length);

                    totalBytesRead += bytesRead;

                    if (bytesRead == 0)
                    {
                        hashAlgorithm.TransformFinalBlock(oldBuffer, 0, oldBytesRead);
                    }
                    else
                    {
                        hashAlgorithm.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0);
                    }

                    BackgroundWorker.ReportProgress((int)((double)totalBytesRead * 100 / size));
                } while (bytesRead != 0);

                e.Result = hashAlgorithm.Hash;
            }
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            StringBuilder sb;

            sb = new StringBuilder();

            ProgressPercentage.Visible = false;
            ProgressBar.Visible = false;
            StatusText.Text = "";

            foreach (byte b in (byte[]) e.Result)
            {
                sb.AppendFormat("{0:X2}", b);
            }
            HashTextbox.Text = sb.ToString();
            
        }

        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ProgressBar.Value = e.ProgressPercentage;
            ProgressPercentage.Text = e.ProgressPercentage + "%";
        }



What I have tried:

if (backgroundWorker1.IsBusy == true)
{

backgroundWorker1.CancelAsync();
while (backgroundWorker1.IsBusy == true)
{
backgroundWorker1.CancelAsync();
}

backgroundWorker1.Dispose();

}

backgroundWorker1.RunWorkerAsync();

解决方案

And, what happened when you tried your code ? Was there an error ? Did it not do something you expected it to ?

You need to study the documentation and example on MSDN: [^].

Set the Property 'WorkerSupportsCancellation of the BackgroundWorker to true, and check the 'CancellationPending Property inside the loop in your 'DoWork method; if 'CancellationPending is 'true set the e.Cancel EventArgs Property to 'true.

Call 'CancelAsynch to stop the Worker. The example on MSDN demonstrates everything you need to know.

Copying code you find on the web and not actually studying documentation, or searching CodeProject or StackOverFlow for examples, or tips, is a good way to make sure you do not progress in learning how to program.

Think how good you are going to feel as you begin to know you are actually mastering the power of the .NET and the C# language, how you are going to say to yourself: "well, that hard work was worth it." :)


这篇关于C#如何正确停止后台工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆