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(); } } }