C# 文件去仅仅读工具-线程-技术&分享
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# 文件去仅仅读工具-线程-技术&分享的更多相关文章
- 怎样取消不能改动(仅仅读打开)的word文件的password
作者:iamlaosong 朋友给我一个文档,是加了防改动password的,希望我能帮其取消.由于须要原文档的格式,取消方法例如以下(office2007环境): 1.打开文件.文件打开时,提演示样 ...
- 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 ...
- Windows下获取Dump文件以及进程下各线程调用栈的方法总结(转)
1. Dump文件的用途 Dump文件, 主要用于诊断一个进程的运行状态,尤其是碰到崩溃(Crash)或者挂起(hang)不响应时,需要分析它的工作状态. 除了平时常见的attach到这个进程, 分 ...
- 【转载】C#工具类:实现文件操作File的工具类
在应用程序的开发中,文件操作的使用基本上是必不可少的,FileStream类.StreamWriter类.Directory类.DirectoryInfo类等都是文件操作中时常涉及到的类,我们可以通过 ...
- txt文件按行处理工具类(可以截取小说、分析日志等)【我】
txt文件按行处理工具类(可以分析日志.截取小说等) package file; import java.io.BufferedReader; import java.io.BufferedWrite ...
- 文件 File 常见操作 工具 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- 【java并发】传统线程技术中创建线程的两种方式
传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...
- C++的std::string的“读时也拷贝”技术!
C++的std::string的读时也拷贝技术! 嘿嘿,你没有看错,我也没有写错,是读时也拷贝技术.什么?我的错,你之前听说写过时才拷贝,嗯,不错的确有这门技术,英文是Copy On Write,简写 ...
- day9 python学习 文件的操作 读 写 seek
文件的操作 1 文件的打开操作: 文件句柄 = open('文件路径', '模式') f=open('wangyakun','a+',encoding='utf-8') #文件名, 如果是绝对路径 ...
随机推荐
- HashMap面试题:90%的人回答不上来
在java面试中集合类似乎已经是绕不开的话题,对于一个中高级java程序员来说如果对集合类的内部原理不了解,基本上面试都会被pass掉.下面从面试官的角度来聊聊一个候选者应该对HashMap了解到什么 ...
- SElinux用户管理操作
查看当前用户上下文 id -Z 查看登陆的用户和其对应的SELinux用户 semanage login -l 改变用户和SELinux的对应关系 semanage login -a选项能改变,-s用 ...
- 用户需求与NABCD分析
用户需求与NABCD分析 目录 项目简介 用户需求分析 调研途径 问卷情况说明 问卷反馈与分析 NABCD分析 Need 需求 Approach 途径 Benefit 好处 Competitors 竞 ...
- [深度学习]实现一个博弈型的AI,从五子棋开始(1)
好久没有写过博客了,多久,大概8年???最近重新把写作这事儿捡起来……最近在折腾AI,写个AI相关的给团队的小伙伴们看吧. 搞了这么多年的机器学习,从分类到聚类,从朴素贝叶斯到SVM,从神经网络到深度 ...
- JS中encodeURI,escape,encodeURIComponent区别
js对文字进行编码涉及3个函数:escape,encodeURI,encodeURIComponent,相应3个解码函数:unescape,decodeURI,decodeURIComponent 1 ...
- Asp.Net MVC 中的 Cookie(译)
Asp.Net MVC 中的 Cookie(译) Cookie Cookie是请求服务器或访问Web页面时携带的一个小的文本信息. Cookie为Web应用程序中提供了一种存储特定用户信息的方法.Co ...
- 有序GUID
背景 常见的一种数据库设计是使用连续的整数为做主键,当新的数据插入到数据库时,由数据库自动生成.但这种设计不一定适合所有场景. 随着越来越多的使用Nhibernate.EntityFramework等 ...
- 如何创建 Swarm 集群?- 每天5分钟玩转 Docker 容器技术(95)
本节我们将创建三节点的 swarm 集群. swarm-manager 是 manager node,swarm-worker1 和 swarm-worker2 是 worker node. 所有节点 ...
- 激光相机数据融合(5)--Gazebo仿真数据融合
这一节将用ROS+Gazebo 环境获取激光获取点云,并用PCL和OPENCV处理,源代码在:https://github.com/ZouCheng321/5_laser_camera_sim 由于激 ...
- Redis安装及使用笔记
windows下安装Redis 1.下载Redis的软件包 Redis on github; 2.将软件解压到服务器软件目录; 3.在命令行运行此命令: ./redis-server redis.wi ...