C # File Read-Only tool-thread-Technology & amp; Share

Source: Internet
Author: User


<喎?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 remove read-only {public partial class Form1: Form {public delegate void MyDelegate (string fileName); private string _ errorMessage = ""; publi C void DelegateMethod (string fp) {textBox2.Text = fp + "\ r \ n" + textBox2.Text; textBox2.SelectionStart = textBox2.Text. length; textBox2.ScrollToCaret ();} public Form1 () {InitializeComponent ();} private void openfiledialog#fileok (object sender, CancelEventArgs e) {}// function name: button2_Click // function: select the file path // input parameter: object sender, EventArgs e // output parameter: no private void button2_Click (object sender, EventArgs E) // select the file path {FolderBrowserDialog fbd = new FolderBrowserDialog (); fbd. showDialog (); string folderName = fbd. selectedPath; // obtain the selected folder path textBox1.Text = folderName;} private void button#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 = "yes"; LableMessage. foreColor = Color. red ;}} catch (Exception ex) {MessageBox. show ("file path problem, please reselect path") ;}} 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 textbox#textchanged (object sender, eventArgs e) {LableMessage. text = "no"; LableMessage. foreColor = Color. black ;}}}

 
 

 
Using System; using System. Collections. Generic; using System. Linq; using System. Text; namespace Mysoft. Common. Multithread {////// Interface for background execution ///Public interface IBackgroundExecute {////// When the execution fails, obtain the specific error message ///String ErrorMessage {get ;}////// Update step event ///Event UpdateStepDelegate OnUpdateStep ;////// Update the progress bar event in the step ///Event wait mstepdelegate on1_mstep ;////// Execute the service //////
 
  
Returns true for execution results; otherwise, returns false.
 Bool Exec ();}////// Update the parameters of the execution step event ///Public class UpdateStepEventArg: EventArgs {public string StepInfo; public int StepMaxCount ;}////// Step-by-step event parameters ///Public class extends mstepeventarg: EventArgs {public int StepCount = 1; public static extends mstepeventarg SingleStepArg = new extends mstepeventarg ();}////// Update step delegate //////The sender.///The e.Public delegate void UpdateStepDelegate (object sender, UpdateStepEventArg e );////// Step-by-step delegation //////The sender.///The e.Public delegate void initialize mstepdelegate (object sender, receivmstepeventarg e );}
Using System; using System. Collections. Generic; using System. Linq; using System. Text; namespace Mysoft. Common. Multithread {////// Interface for displaying the progress bar ///Public interface IProgressDlg {////// Obtain or set the total number of steps ///Int StepCount {get; set ;}////// Get or set whether cancellation is allowed ///Bool AllowCancel {get; set ;}////// Increment the scroll bar ///Void merge mstep ();////// Increment the scroll bar based on the specified number of progresses //////Number of progress to be incrementedVoid merge mstep (int stepCount );////// Set the displayed information //////Information to be displayedVoid 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 member ////// Obtain or set the total number of steps ///Int IProgressDlg. StepCount {get {return _ stepCount;} set {_ stepCount = value; _ nowStep = 0 ;}}////// Get or set whether cancellation is allowed ///Bool IProgressDlg. allowCancel {get {return this. btnCancel. enabled;} set {this. btnCancel. enabled = false ;}} void IProgressDlg. required mstep () {Interlocked. increment (ref _ progressCount);} void IProgressDlg. required mstep (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 (required mstep_internal) ;}}_ threadState = ThreadState. stopped;} private void required mstep_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 {////// Run the progress bar and use multiple threads to execute the program ///Public class ProgressRun: IRunObject {public class ExecCompletedEventArg {private bool _ isSucceed; private bool _ isException; private string _ message; public partition (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 response _ progressDlg; private response Cute _ 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 _ errorMessa Ge ;}} public bool Run (IBackgroundExecute backgroupExecute, int stepCount) {if (_ isExecute) {throw new System. exception ("the current background program is executing operations");} _ 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. ondomainmstep + = new jsonmstepdelegate (backgroupexecute_ondomainmstep); try {if (! BackgroupExecute. exec () {_ isSuccess = false; _ errorMessage = backgroupExecute. errorMessage;} catch (System. exception ex) {_ isSuccess = false; _ errorMessage = ex. message;} _ progressDlg. hide ();} void backgroupexecute_on1_mstep (object sender, receivmstepeventarg e) {_ progressDlg. required mstep ();} void backgroupExecute_OnUpdateStep (object sender, UpdateStepEventArg e) {_ progressDlg. nextSetp (e. stepMaxCount, e. stepInfo) ;}# region IRunObject member 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(); } }}
      
     
    
   
  
 


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.