1

I have this code in c# .net core. I want to know that can this code corrupt the file if I try to cancel it. If yes how can I solve this issue?

private async Task<string> MoveFile(string sourcePath, string destinationPath, CancellationToken token)
    {
        Thread threadToCancel = null;
        var tcs = new TaskCompletionSource<string>();
        
        Task.Factory.StartNew(() =>
        {
            //Capture the thread  
            threadToCancel = Thread.CurrentThread;
            File.Move(sourcePath, destinationPath);
        }, TaskCreationOptions.LongRunning);

        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                if (token.IsCancellationRequested && threadToCancel != null)
                {
                    threadToCancel.Abort();//abort long running thread  
                    tcs.SetResult("Cancled");
                    return tcs.Task.Result;
                }
                Thread.Sleep(500);
            }
        });

        tcs.SetResult("Completed");
        return tcs.Task.Result;
    }
  • 9
    `Thread.Abort` is always a bad idea. This looks very contrived. What's the problem you are trying to solve? – TheGeneral Jun 25 '20 at 08:51
  • 3
    all I can say for sure here is that I can't guarantee that it *won't* corrupt the file... it certainly looks like it absolutely *could* do a lot of harm; the number of times when aborting a thread is a good idea is essentially zero – Marc Gravell Jun 25 '20 at 09:18
  • 1
    `If yes how can I solve this issue?` Don't abort the thread. – mjwills Jun 25 '20 at 09:38
  • @TheGeneral I want ability to cancel the file transfer. –  Jun 25 '20 at 09:46
  • Likely, the most reliable way to do this with your requirement, is to open 2 file streams and copy chunks at a time. This way you have fine-grained control over the cancel and can clean up the file afterwards. However this is not the same as MoveFile which is derived from an Win32 api call and is managed by the operating system, though you get the advantage of a cancel without corrupting your app domain, setting appropriate file read write modes, chunk size ect, ect, ect – TheGeneral Jun 25 '20 at 09:49
  • Related to @TheGeneral's mention of `MoveFile()`, Win32 also provides a [`MoveFileWithProgress()` function](https://docs.microsoft.com/windows/win32/api/winbase/nf-winbase-movefilewithprogressw). You pass it an [`LPPROGRESS_ROUTINE` callback function](https://docs.microsoft.com/windows/win32/api/winbase/nc-winbase-lpprogress_routine) which receives progress updates and allows for cancellation. It's on [pinvoke.net](http://pinvoke.net/default.aspx/kernel32/MoveFileWithProgress.html) but evidently not part of the [`PInvoke.Kernel32` library](https://www.nuget.org/packages/PInvoke.Kernel32). – Lance U. Matthews Jun 29 '20 at 04:10

0 Answers0