取消按钮单击时取消FileCopy操作 [英] Canceling FileCopy operation on cancel button click

查看:91
本文介绍了取消按钮单击时取消FileCopy操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有线程,开始点击开始按钮并执行文件复制操作。

OnCancel按钮单击导致线程停止处理并删除复制的文件。

我怎么能实现这个目标?

My application have thread which get started on start button click and do file copy operation.
OnCancel button click causes thread to stop the processing and delete copied file.
how Can I achieve this?

推荐答案

你可以用很少的逻辑重写你的代码:



阅读以小块文件并将其写入目的地。定期检查是否有人要求取消,如果检测到,请停止写入并关闭文件。
You can rewrite your code with little logic:

Read the file in small chunks and write it out to the destination. Periodically check whether you've been asked to cancel and if you detect that, stop writing and close the files.


对于上述逻辑,代码示例附在此处:



For the above logic, the code sample is attached here:

void CopyStream(Stream inputStream, Stream outputStream)
{
    var buffer = new byte[1024];

    int bytesRead;
    while((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        outputStream.Write(buffer, 0, bytesRead);
        if(cancelled){
           // cleanup

           return;
        }
    }
}


这篇关于取消按钮单击时取消FileCopy操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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