程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 文件去只讀工具-線程-技術&分享

C# 文件去只讀工具-線程-技術&分享

編輯:C#入門知識

\

<喎?http://www.Bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHByZSBjbGFzcz0="brush:java;">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 pathList = new List(); string[] dirPathes = Directory.GetDirectories(dirPath, "*.*", SearchOption.TopDirectoryOnly); foreach (var dp in dirPathes) { if (!Directory.Exists(dp)) { continue; } pathList.Add(dp); } ThreadPool thread = new ThreadPool(pathList); thread.MaxThreadCount = 6; thread.OnProcessData += new ThreadPool.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
{
    /// 
    /// 後台執行接口
    /// 
    public interface IBackgroundExecute
    {
        /// 
        /// 當執行失敗時,獲取具體的錯誤信息
        /// 
        string ErrorMessage
        {
            get;
        }

        /// 
        /// 更新步驟事件
        /// 
        event UpdateStepDelegate OnUpdateStep;

        /// 
        ///更新步驟內進度條事件
        /// 
        event PerformStepDelegate OnPerformStep;

        /// 
        /// 執行服務
        /// 
        /// 執行成果返回true,否則返回false
        bool Exec();
    }

    /// 
    /// 更新執行步驟事件參數
    /// 
    public class UpdateStepEventArg : EventArgs
    {
        public string StepInfo;

        public int StepMaxCount;
    }

    /// 
    /// 步驟遞增事件參數
    /// 
    public class PerformStepEventArg : EventArgs
    {
        public int StepCount = 1;

        public static PerformStepEventArg SingleStepArg = new PerformStepEventArg();
    }

    /// 
    /// 更新步驟委托
    /// 
    /// The sender.
    /// The e.
    public delegate void UpdateStepDelegate(object sender, UpdateStepEventArg e);

    /// 
    /// 遞增步驟委托
    /// 
    /// The sender.
    /// The e.
    public delegate void PerformStepDelegate(object sender, PerformStepEventArg e);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mysoft.Common.Multithread
{
    /// 
    /// 顯示進度條的對話框接口
    /// 
    public interface IProgressDlg
    {
        /// 
        /// 獲取或設置總步驟數
        /// 
        int StepCount
        {
            get;
            set;
        }

        /// 
        /// 獲取或設置是否允許取消
        /// 
        bool AllowCancel
        {
            get;
            set;
        }

        /// 
        /// 遞增滾動條
        /// 
        void PerformStep();

        /// 
        /// 根據指定的進度數來遞增滾動條
        /// 
        /// 要遞增的進度數
        void PerformStep(int stepCount);

        /// 
        /// 設置顯示的信息
        /// 
        /// 要顯示的信息
        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 成員

        /// 
        /// 獲取或設置總步驟數
        /// 
        int IProgressDlg.StepCount
        {
            get
            {
                return _stepCount;
            }
            set
            {
                _stepCount = value;
                _nowStep = 0;
            }
        }

        /// 
        /// 獲取或設置是否允許取消
        /// 
        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(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
{
    /// 
    /// 運行進度條,並采用多線程來執行程序
    /// 
    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 : IDisposable
    {
        public delegate void ProcessDataDelegate(T data);

        private Queue _dataList;
        private int _maxThreadCount = 100;
        private ThreadState _threadState = ThreadState.Unstarted;
        private int _threadCount = 0;

        public event ProcessDataDelegate OnProcessData;

        public ThreadPool()
        {
            _dataList = new Queue();
        }

        public ThreadPool(IEnumerable datas)
        {
            _dataList = new Queue(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 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. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved