Reducing duplicate error handling code in C#?

后端 未结 4 1317
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 19:08

I\'ve never been completely happy with the way exception handling works, there\'s a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to

4条回答
  •  既然无缘
    2020-12-29 19:19

    Just wondering, what do you feel your method leaves to be desired? You could replace the anonymous delegate with a.. named? delegate, something like

        public delegate void IoOperation(params string[] parameters);
    
        public void FileDeleteOperation(params string[] fileName)
        {
            File.Delete(fileName[0]);
        }
    
        public void FileCopyOperation(params string[] fileNames)
        {
            File.Copy(fileNames[0], fileNames[1]);
        }
    
        public void RetryFileIO(IoOperation operation, params string[] parameters)
        {
            RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));
            bool success = false;
            while (!success)
            {
                try
                {
                    operation(parameters);
                    success = true;
                }
                catch (IOException e)
                {
                    if (fileIORetryTimer.HasExceededRetryTimeout)
                    {
                        throw;
                    }
                    fileIORetryTimer.SleepUntilNextRetry();
                }
            }
        }
    
        public void Foo()
        {
            this.RetryFileIO(FileDeleteOperation, "L:\file.to.delete" );
            this.RetryFileIO(FileCopyOperation, "L:\file.to.copy.source", "L:\file.to.copy.destination" );
        }
    

提交回复
热议问题