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

C# 文件去仅仅读工具-线程-技术&amp;分享的更多相关文章

  1. 怎样取消不能改动(仅仅读打开)的word文件的password

    作者:iamlaosong 朋友给我一个文档,是加了防改动password的,希望我能帮其取消.由于须要原文档的格式,取消方法例如以下(office2007环境): 1.打开文件.文件打开时,提演示样 ...

  2. c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习

    c#中@标志的作用   参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...

  3. Windows下获取Dump文件以及进程下各线程调用栈的方法总结(转)

    1. Dump文件的用途 Dump文件, 主要用于诊断一个进程的运行状态,尤其是碰到崩溃(Crash)或者挂起(hang)不响应时,需要分析它的工作状态.  除了平时常见的attach到这个进程, 分 ...

  4. 【转载】C#工具类:实现文件操作File的工具类

    在应用程序的开发中,文件操作的使用基本上是必不可少的,FileStream类.StreamWriter类.Directory类.DirectoryInfo类等都是文件操作中时常涉及到的类,我们可以通过 ...

  5. txt文件按行处理工具类(可以截取小说、分析日志等)【我】

    txt文件按行处理工具类(可以分析日志.截取小说等) package file; import java.io.BufferedReader; import java.io.BufferedWrite ...

  6. 文件 File 常见操作 工具 MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  7. 【java并发】传统线程技术中创建线程的两种方式

    传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...

  8. C++的std::string的“读时也拷贝”技术!

    C++的std::string的读时也拷贝技术! 嘿嘿,你没有看错,我也没有写错,是读时也拷贝技术.什么?我的错,你之前听说写过时才拷贝,嗯,不错的确有这门技术,英文是Copy On Write,简写 ...

  9. day9 python学习 文件的操作 读 写 seek

    文件的操作 1   文件的打开操作: 文件句柄 = open('文件路径', '模式') f=open('wangyakun','a+',encoding='utf-8') #文件名, 如果是绝对路径 ...

随机推荐

  1. 双色球js

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  2. 巧用ecshop做淘宝客

    一.第一步 下载文件,可以在http://www.ecshop.com/下载ecshop各个版本的安装包,安装好ECSHOP,然后通过PTF工具下载2个文件到本地进行修改.这个2个文件分别是goods ...

  3. solr索引库的创建

    solr索引库的创建 一.找到你安装的[solrhome]目录(我的是这个) 二.进入该目录 三.选择其中任意一个索引库复制一份到该目录下并更名为要创建的索引库名称 四.进入[myindex]目录下, ...

  4. From missionary to firebrand--Eisle Tu [20160102]

    From missionary to firebrand   杜叶锡恩(1913年(癸丑年)-2015年(乙未年),英文名字Elsie Hume Elliot Tu,丈夫是教育家杜学魁.她是香港著名的 ...

  5. TEXT和BLOB区别

    A BLOB is a binary large object that can hold a variable amount of data. The four BLOB types are TIN ...

  6. jq 时间计算

    -(function($){ var caculation = function(gap){ var minutes = 1000 * 60 var hours = minutes * 60 var ...

  7. C++语言中的类型(二)

    --分门别类是简化事物最有效的方式. C++语言的强大能力的体现在对程序员自定义数据类型的支持.C++语言主要的一个设计目标就是让程序员自定义的数据类型像内置类型一样好用. 一.自定义数据类型 数据类 ...

  8. Audio Source组件及相关API

    Audio Source:声音组件.需要与 Audio Listener 配合使用,Main Camera 会默认有 Audio Lisetener. Audio Clip:声音片段.指定需要播放的音 ...

  9. Less的!important关键字

    Less的!important关键字 在调用 mixin 时,如果在后面追加 !important 关键字,就可以将 mixin 里面的所有属性都标记为 !important.如,以下Less代码: ...

  10. 【Win 10 应用开发】在后台播放视频

    从 1607 (14393)版本开始,MediaPlayer 类就可以在前台与后台之间无缝播放,你不必再考虑前台与后之间的通信,所以从 14393 开始,你就不需要再用 BackgroundMedia ...