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. 4. ZooKeeper 基本操作

    ZooKeeper的数据模型及其API支持以下九个基本操作: 操作 描述 create 在ZooKeeper命名空间的指定路径中创建一个znode delete 从ZooKeeper命名空间的指定路径 ...

  2. pgjdbc源码分析

    一. 源代码目录结构 pgjdbc的源码结构如下图: 那么我们来一一看看各个模块都是做什么的吧. 1 core 该目录是程序的核心模块目录. 这里实现了大部分pgjdbc的基类和接口,例如statem ...

  3. C#编写的艺术字类方法

    代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing ...

  4. react 体验 react与vue的比较

    用了 vue 大半年了,不过我在2016年暑假的时候就看到了 react 这个项目,有点想学习一番,之前学习的都是基础语法和一些基础用法吧,总的来说 mvvm 框架确实都很相似,会一个就可以了; 今天 ...

  5. Linux系列教程(二十四)——Linux的系统管理

    上篇博客介绍了Linux的服务管理,不管是以RPM包安装的服务,还是通过源码包安装的服务,万能启动服务的方法都可以通过 /绝对路径/启动脚本名 start .而通过 RPM 包安装的服务还可以通过 s ...

  6. formData实现图片上传

    前言 在 上一篇 已经实现了图片预览,那么如何上传图片呢?有两种思路: 1.将图片转化为dataURL(base64),这样就成为了一串字符串,再传到服务端.不过这样缺点很多,数据量比转换之前增加1/ ...

  7. 简述Handler机制

    我会对android的消息处理有三个核心类逐步介绍,他们分别是:Looper,Handler和Message.其实还有一Message Queue(消息队列),知道它是队列即可,就像我们所熟知的数组, ...

  8. sqoop的导入导出

    1.知道某列的值的增量导入(mysql------>文件) bin/sqoop import \--connect jdbc:mysql://bigdatcdh01:3306/test \--u ...

  9. java八大基本数据类型

    java中八大数据类型的储存空间以及使用场景表示如下 )1.int:4字节,可以表示的数为-2^31 - 2^31-1.整数的默认类型.封装类也如此 .整数相除的时候,会舍弃小数部分.结果也是整数,例 ...

  10. 一个非常好用的图片切割工具(c# winform开发) 附源码

    本人业余时间开发了一个图片切割工具,非常好用,也很灵活! 特别对大型图片切割,更能体现出该软件的优势! 开发工具为winform,源码下载地址:http://download.csdn.net/dow ...