C# 文件去只读工具-线程-技术&分享

来源:互联网 发布:广东淘宝司法拍卖网站 编辑:程序博客网 时间:2024/05/19 14:01


using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using Mysoft.Common.Multithread;namespace 除去只读{    public partial class Form1 : Form    {        public delegate void MyDelegate(string fileName);        private string _errorMessage = "";        public void DelegateMethod(string fp)        {            textBox2.Text = fp + "\r\n" + textBox2.Text;            textBox2.SelectionStart = textBox2.Text.Length;            textBox2.ScrollToCaret();        }        public Form1()        {            InitializeComponent();        }        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)        {        }        //函数名:button2_Click        //函数功能:选择文件路径        //输入参数:object sender, EventArgs e        //输出参数:无        private void button2_Click(object sender, EventArgs e)//选择文件路径        {            FolderBrowserDialog fbd = new FolderBrowserDialog();            fbd.ShowDialog();            string folderName = fbd.SelectedPath; //获得选择的文件夹路径            textBox1.Text = folderName;        }        private void button1_Click(object sender, EventArgs e)        {            try            {                string dirPath = textBox1.Text;                if (dirPath != "")                {                    textBox2.Text = "";                    List<string> pathList = new List<string>();                    string[] dirPathes = Directory.GetDirectories(dirPath, "*.*", SearchOption.TopDirectoryOnly);                    foreach (var dp in dirPathes)                    {                        if (!Directory.Exists(dp))                        {                            continue;                        }                                               pathList.Add(dp);                    }                    ThreadPool<string> thread = new ThreadPool<string>(pathList);                    thread.MaxThreadCount = 6;                    thread.OnProcessData += new ThreadPool<string>.ProcessDataDelegate(SetReadOnly);                    thread.Start(false);                    LableMessage.Text = "是";                    LableMessage.ForeColor = Color.Red;                }            }            catch (Exception ex)            {                MessageBox.Show("文件路径存在问题,请重新选择路径");            }        }        private void SetReadOnly(string dirPath)        {            try            {                string[] dirPathes = Directory.GetDirectories(dirPath, "*.*", SearchOption.AllDirectories);                foreach (var dp in dirPathes)                {                    if (!Directory.Exists(dp))                    {                        continue;                    }                    if (dp.Substring(dp.ToString().Length - 3, 3).ToUpper() == "bin".ToUpper() || dp.Substring(dp.ToString().Length - 3, 3).ToUpper() == "obj".ToUpper())                    {                        DirectoryInfo dir = new DirectoryInfo(dp);                        dir.Attributes = FileAttributes.Normal & FileAttributes.Directory;                        string[] filePathes = Directory.GetFiles(dp, "*.*", SearchOption.AllDirectories);                        foreach (var fp in filePathes)                        {                            File.SetAttributes(fp, System.IO.FileAttributes.Normal);                            object[] myArray = new object[1];                            myArray[0] = fp;                            BeginInvoke(new MyDelegate(DelegateMethod), myArray);                        }                        }                                                 }                          }            catch (Exception ex)            {                _errorMessage = ex.Message;            }            finally            {            }        }        private void textBox2_TextChanged(object sender, EventArgs e)        {        }        private void LableMessage_Click(object sender, EventArgs e)        {        }        private void textBox1_TextChanged(object sender, EventArgs e)        {            LableMessage.Text = "否";            LableMessage.ForeColor = Color.Black;        }    }}

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Mysoft.Common.Multithread{    /// <summary>    /// 后台执行接口    /// </summary>    public interface IBackgroundExecute    {        /// <summary>        /// 当执行失败时,获取具体的错误信息        /// </summary>        string ErrorMessage        {            get;        }        /// <summary>        /// 更新步骤事件        /// </summary>        event UpdateStepDelegate OnUpdateStep;        /// <summary>        ///更新步骤内进度条事件        /// </summary>        event PerformStepDelegate OnPerformStep;        /// <summary>        /// 执行服务        /// </summary>        /// <returns>执行成果返回true,否则返回false</returns>        bool Exec();    }    /// <summary>    /// 更新执行步骤事件参数    /// </summary>    public class UpdateStepEventArg : EventArgs    {        public string StepInfo;        public int StepMaxCount;    }    /// <summary>    /// 步骤递增事件参数    /// </summary>    public class PerformStepEventArg : EventArgs    {        public int StepCount = 1;        public static PerformStepEventArg SingleStepArg = new PerformStepEventArg();    }    /// <summary>    /// 更新步骤委托    /// </summary>    /// <param name="sender">The sender.</param>    /// <param name="e">The e.</param>    public delegate void UpdateStepDelegate(object sender, UpdateStepEventArg e);    /// <summary>    /// 递增步骤委托    /// </summary>    /// <param name="sender">The sender.</param>    /// <param name="e">The e.</param>    public delegate void PerformStepDelegate(object sender, PerformStepEventArg e);}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Mysoft.Common.Multithread{    /// <summary>    /// 显示进度条的对话框接口    /// </summary>    public interface IProgressDlg    {        /// <summary>        /// 获取或设置总步骤数        /// </summary>        int StepCount        {            get;            set;        }        /// <summary>        /// 获取或设置是否允许取消        /// </summary>        bool AllowCancel        {            get;            set;        }        /// <summary>        /// 递增滚动条        /// </summary>        void PerformStep();        /// <summary>        /// 根据指定的进度数来递增滚动条        /// </summary>        /// <param name="stepCount">要递增的进度数</param>        void PerformStep(int stepCount);        /// <summary>        /// 设置显示的信息        /// </summary>        /// <param name="info">要显示的信息</param>        void NextSetp(int progressCount, string info);        IRunObject RunObject        {            set;        }        void Show();        void Hide();    }}

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Mysoft.Common.Multithread{    public interface IRunObject    {        void Run();    }}

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;namespace Mysoft.Common.Multithread{    public partial class ProgressDlg : Form, IProgressDlg    {        private int _stepCount;        private Thread _timeThread;        private ThreadState _threadState;        private int _nowStep = 0;        private int _progressCount;        private IRunObject _runObject;        public ProgressDlg()        {            InitializeComponent();        }        #region IProgressDlg 成员        /// <summary>        /// 获取或设置总步骤数        /// </summary>        int IProgressDlg.StepCount        {            get            {                return _stepCount;            }            set            {                _stepCount = value;                _nowStep = 0;            }        }        /// <summary>        /// 获取或设置是否允许取消        /// </summary>        bool IProgressDlg.AllowCancel        {            get            {                return this.btnCancel.Enabled;            }            set            {                this.btnCancel.Enabled = false;            }        }        void IProgressDlg.PerformStep()        {            Interlocked.Increment(ref _progressCount);        }        void IProgressDlg.PerformStep(int stepCount)        {            Interlocked.Add(ref _progressCount, stepCount);        }        void IProgressDlg.NextSetp(int progressCount, string info)        {            this.Invoke(new Action<int, string>(NextSetp_internal), progressCount, info);        }        IRunObject IProgressDlg.RunObject        {            set            {                _runObject = value;            }        }        void IProgressDlg.Show()        {            this.ShowDialog();        }        void IProgressDlg.Hide()        {            this.Invoke(new Action(Close_internal));        }        #endregion        private void Close_internal()        {            _threadState = ThreadState.StopRequested;            _timeThread.Abort();            this.Close();        }        private void NextSetp_internal(int progressCount, string info)        {            _nowStep++;            lblInfo.Text = string.Format("({0}/{1})", _nowStep, _stepCount) + info;            progressBar1.Maximum = progressCount;            progressBar1.Value = 0;            Interlocked.Exchange(ref _progressCount, 0);        }        private void timeThreadProcess()        {            while (_threadState == ThreadState.Running)            {                Thread.Sleep(100);                if (_progressCount > 0)                {                    this.Invoke(                        new Action(PerformStep_internal)                    );                }            }            _threadState = ThreadState.Stopped;        }        private void PerformStep_internal()        {            if (_progressCount > 0)            {                progressBar1.Value += Interlocked.Exchange(ref _progressCount, 0);            }        }        private void ProgressDlg_Load(object sender, EventArgs e)        {            _timeThread = new Thread(new ThreadStart(timeThreadProcess));            _threadState = ThreadState.Running;            _timeThread.Start();            _runObject.Run();        }    }}

using System;using System.Collections.Generic;using System.ComponentModel;using System.Text;namespace Mysoft.Common.Multithread{    /// <summary>    /// 运行进度条,并采用多线程来执行程序    /// </summary>    public class ProgressRun : IRunObject    {        public class ExecCompletedEventArg        {            private bool _isSucceed;            private bool _isException;            private string _message;            public ExecCompletedEventArg(bool isSucceed, string message)            {                _isSucceed = isSucceed;                _isException = false;                _message = message;            }            public ExecCompletedEventArg(string message)            {                _isSucceed = false;                _isException = true;                _message = message;            }            public bool IsSucceed            {                get                {                    return _isSucceed;                }            }            public bool IsException            {                get                {                    return _isException;                }            }            public string Message            {                get                {                    return _message;                }            }        }        public delegate void ExecCompletedDelegate(object sender, ExecCompletedEventArg e);        private BackgroundWorker _backgroundWorker = new BackgroundWorker();        private bool _isExecute = false;        private IProgressDlg _progressDlg;        private IBackgroundExecute _backgroupExecute;        private int _stepCount;        private bool _isSuccess = true;        private string _errorMessage;        public ProgressRun()            : this(new ProgressDlg())        {        }        public ProgressRun(IProgressDlg progressDlg)        {            _progressDlg = progressDlg;            _progressDlg.RunObject = this;            _backgroundWorker.DoWork += new DoWorkEventHandler(_backgroundWorker_DoWork);        }        public string ErrorMessage        {            get            {                return _errorMessage;            }        }        public bool Run(IBackgroundExecute backgroupExecute, int stepCount)        {            if (_isExecute)            {                throw new System.Exception("当前后台程序正在执行操作");            }            _backgroupExecute = backgroupExecute;            _stepCount = stepCount;            _progressDlg.Show();            return _isSuccess;        }        void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)        {            _isExecute = true;            IBackgroundExecute backgroupExecute = (IBackgroundExecute)e.Argument;            backgroupExecute.OnUpdateStep += new UpdateStepDelegate(backgroupExecute_OnUpdateStep);            backgroupExecute.OnPerformStep += new PerformStepDelegate(backgroupExecute_OnPerformStep);            try            {                if (!backgroupExecute.Exec())                {                    _isSuccess = false;                    _errorMessage = backgroupExecute.ErrorMessage;                }            }            catch (System.Exception ex)            {                _isSuccess = false;                _errorMessage = ex.Message;            }            _progressDlg.Hide();        }        void backgroupExecute_OnPerformStep(object sender, PerformStepEventArg e)        {            _progressDlg.PerformStep();        }        void backgroupExecute_OnUpdateStep(object sender, UpdateStepEventArg e)        {            _progressDlg.NextSetp(e.StepMaxCount, e.StepInfo);        }        #region IRunObject 成员        void IRunObject.Run()        {            _backgroundWorker.RunWorkerAsync(_backgroupExecute);            _progressDlg.StepCount = _stepCount;        }        #endregion    }}

using System;using System.Collections.Generic;using System.Threading;using System.Text;namespace Mysoft.Common.Multithread{    public class ThreadPool<T> : IDisposable    {        public delegate void ProcessDataDelegate(T data);        private Queue<T> _dataList;        private int _maxThreadCount = 100;        private ThreadState _threadState = ThreadState.Unstarted;        private int _threadCount = 0;        public event ProcessDataDelegate OnProcessData;        public ThreadPool()        {            _dataList = new Queue<T>();        }        public ThreadPool(IEnumerable<T> datas)        {            _dataList = new Queue<T>(datas);        }        public int MaxThreadCount        {            get            {                return _maxThreadCount;            }            set            {                _maxThreadCount = value;            }        }        public ThreadState State        {            get            {                if (_threadState == ThreadState.Running                    && _threadCount == 0)                {                    return ThreadState.WaitSleepJoin;                }                return _threadState;            }        }        public void AddData(T data)        {            lock (_dataList)            {                _dataList.Enqueue(data);            }            if (_threadState == ThreadState.Running)            {                Interlocked.Increment(ref _threadCount);                StartupProcess(null);            }        }        public void AddData(List<T> data)        {            lock (_dataList)            {                for (int i = 0; i < data.Count; i++)                {                    _dataList.Enqueue(data[i]);                }            }            if (_threadState == ThreadState.Running)            {                Interlocked.Increment(ref _threadCount);                StartupProcess(null);            }        }        public void Start(bool isAsyn)        {            if (_threadState != ThreadState.Running)            {                _threadState = ThreadState.Running;                if (isAsyn)                {                    _threadCount = 1;                    ThreadPool.QueueUserWorkItem(StartupProcess);                }                else                {                    Interlocked.Increment(ref _threadCount);                    StartupProcess(null);                    while (_threadCount != 0)                    {                        Thread.Sleep(100);                    }                }            }        }        public void Stop()        {            if (_threadState != ThreadState.Stopped                || _threadState != ThreadState.StopRequested)            {                _threadState = ThreadState.StopRequested;                if (_threadCount > 0)                {                    while (_threadState != ThreadState.Stopped)                    {                        Thread.Sleep(500);                    }                }                _threadState = ThreadState.Stopped;            }        }        private void StartupProcess(object o)        {            if (_dataList.Count > 0)            {                Interlocked.Increment(ref _threadCount);                ThreadPool.QueueUserWorkItem(ThreadProcess);                while (_dataList.Count > 2)                {                    if (_threadCount >= _maxThreadCount)                    {                        break;                    }                    Interlocked.Increment(ref _threadCount);                    ThreadPool.QueueUserWorkItem(ThreadProcess);                }            }            Interlocked.Decrement(ref _threadCount);        }        private void ThreadProcess(object o)        {            T data;            while (_threadState == ThreadState.Running)            {                lock (_dataList)                {                    if (_dataList.Count > 0)                    {                        data = _dataList.Dequeue();                    }                    else                    {                        break;                    }                }                OnProcessData(data);            }            Interlocked.Decrement(ref _threadCount);        }        public void Dispose()        {            Stop();        }    }}


                                             
1 0
原创粉丝点击