111,098
社区成员




int Count;
int ShareCount = 3, SingleCount = 0, LastCount = 0;
string dest = @"E:\Test2\", source = @"E:\Test";
List<FileInfo> list = new List<FileInfo>();
StringBuilder sb = new StringBuilder();
bool stop = false;
public 多线程()
{
if (!Directory.Exists(dest))
Directory.CreateDirectory(dest);
DirectoryInfo di = new DirectoryInfo(source);
foreach (FileInfo f in di.GetFiles())
{
list.Add(f);
}
SingleCount = list.Count / ShareCount;
LastCount = list.Count % ShareCount;
ShareCount = LastCount == 0 ? ShareCount : ShareCount + 1;
sb.Capacity = list.Count * 15;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < ShareCount; i++)
{
Thread thread = new Thread(new ParameterizedThreadStart(CopyFile));
thread.Name = "Thread:" + i;
thread.IsBackground = true;
thread.Start(i);
}
button1.Enabled = false;
}
protected void CopyFile(object i)
{
int j = (int)i;
int tempCount = j * SingleCount + SingleCount;
int totalCount = tempCount > list.Count ? list.Count : tempCount;
for (int c = j * SingleCount; c < totalCount; c++)
{
if (stop)
{
c--;
while (stop)
{
Thread.Sleep(500);
}
}
else
{
File.Copy(list[c].FullName, dest + list[c].Name, true);
Count++;
ShowTextBox(list[c].Name + " Count:" + Count + " " + Thread.CurrentThread.Name.PadLeft(9, ' ') + "\r\n");
ShowProgress();
}
}
}
protected void ShowTextBox(string msg)
{
if (this.textBox1.InvokeRequired)
{
this.textBox1.Invoke(new Action(() => ShowTextBox(msg)));
}
else
{
sb.Append(msg);
if (Count % 100 == 0)
this.textBox1.Text = sb.ToString();
}
}
protected void ShowProgress()
{
if (this.progressBar1.InvokeRequired)
{
this.progressBar1.Invoke(new Action(() => ShowProgress()));
}
else
{
int value = (int)((double)Count / (double)list.Count * 100);
this.progressBar1.Value = value;
label1.Text = value + "%";
}
}
private void button2_Click(object sender, EventArgs e)
{
stop = stop == false ? true : false;
}
thread .Suspend();
thread .Resume();