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. 【框架学习与探究之日志组件--Log4Net与NLog】

    前言 本文欢迎转载,作者原创地址:http://www.cnblogs.com/DjlNet/p/7604340.html 序 近日,天气渐冷,懒惰的脑虫又开始作祟了,导致近日内功修炼迟迟未能进步,依 ...

  2. Thinkphp5 模型 验证器执行顺序问题

    Thinkphp5把模型的验证规则归为一个验证器,这种做法,不知到符不符合大家的心意,反正楼主是比较不爽的 楼主更倾向于tp3.2的验证规则直接写在模型里面,毕竟你的验证规则一般而言是针对模型来验证的 ...

  3. Entity Framework 调用返回标量值的存储过程

    最近项目用到EF,虽然说EF与Linq To SQL有很多地方相似,但是EF(这里指3.5版,4.0版的还没去留意)确实有些地方做得不够方便. 就拿存储过程来说吧,EF里面想调用存储过程不是直接在数据 ...

  4. EF错误

    The model backing the 'XXXXDBContext' context has changed since the database was created. Either man ...

  5. 阿里云CentOS搭建系统

    1.在阿里云网站上购买申请服务器. 2.通过Xshell连接服务器,并用root账户登入. 3.配置java开发环境:(也可以使用阿里云一键部署,自动配置并部署服务器) 一.安装jdk 1.查看Lin ...

  6. 《Metasploit魔鬼训练营》虚拟环境搭建中网络配置的一些问题

    直接使用网上下载与书本配套的虚拟机环境,发现NAT服务器10.10.10.254(192.168.10.254)虽然可以和其他虚拟机ping通,但是连不上网.自然windows xp靶机也连不上网了. ...

  7. let和const命令

    let命令 1.let用来声明变量,类似于var,但只在代码块内有效. { let a = 1; var b = 2; } console.log(a); //a is not defined con ...

  8. Office2016 KMS激活

    Office标准版激活 一新买本子需要安装Office,闲来无事就安装了一款Office Standard 2016,网上许多激活秘钥均已过期,无法激活,无奈下选择KMS激活. KMS下载链接如下: ...

  9. [动态规划]P1004 方格取数

    ---恢复内容开始--- 题目描述 设有N*N的方格图(N<=9),我们将其中的某些方格中填入正整数,而其他的方格中则放 人数字0.如下图所示(见样例): A 0 0 0 0 0 0 0 0 0 ...

  10. 【转】javascript中的LHS与RHS

    原文链接:http://www.cnblogs.com/yangxiaoguai132/p/5064625.html 最近在学习javascript过程中,接触了LHS与RHS的概念,刚开始的时候有点 ...