ถามเรื่องตอนรัน win app ของ c#.net หน่อยครับ ถ้าเป็นโปรแกรมที่มีการ Loop ไม่มาก ตอนโปรแกรม process ถ้าเอาไปคลิกก็ไม่มีปัญหาอะไรหรอกครับ
1. วิธีกากสุด เอา Application.DoEvents() ไปใส่ในลูป เช่น
Code (C#)
private void btn1_Click ( object sender , EventArgs e )
{
for( int i = 0 ; i <= 10 ; ++i )
{
Application.DoEvents();
System.Threading.Thread.Sleep( 1000 );
this.Text = i.ToString();
}
}
2.วิธีปานกลาง ไปศึกษาวิธีการใช้คอนโทรล background worker
3.วิธีเทพสุด ไปศึกษาวิธีการวิธีเขียนโปรแกรมแบบ MultiThreading,parallel processing
คุณ richter เคยเขียนไว้แล้ว ไปอ่านได้ที่นี่ http://www.greatfriends.biz/webboards/msg.asp?b=SURREALIST&id=124393&sw=Task%20Parallel
Date :
2011-04-21 17:19:52
By :
Programmer Of Persia
คุณ Programmer Of Persia ลิ้งท์วิธีที่สามเข้าไม่ได้อ่ะครับ รบกวนขอใหม่ด้วยครับ
Date :
2011-04-22 17:35:16
By :
GhostLocal
ไม่ต้องถึงกับ parallel ก้อได้ค่ะ แยกเขียน loop แบบ long time process ไปเป็นแบบ asyncronous thread ก้อได้
มีมาตั้งแต่ .net 1.0 แล้วค่ะ ยกตัวอย่างก้อพวก BeginExecuteNonQuery หรือ BeginExecuteReader
ของ SqlCommand นั่นก้อได้ค่ะ
Date :
2011-04-22 20:03:21
By :
blurEyes
Blackground Worker ง่ายสุดแล้วครับ ลองหาดูใน web นี้ก็มี หรือถาม อา google ก็เยอะแยะ
Date :
2011-04-22 20:44:34
By :
numenoy
ผมเข้าไปอ่านแล้วครับ แต่ผมสงสัย event ของ background worker ซึ่งมีอยู่ 3 อัน
1.backgroundWorker1_DoWork
2.backgroundWorker1_ProgressChanged
3.backgroundWorker1_RunWorkerCompleted
event ข้อ 1 พอเข้าใจครับคือเป็นการไปเรียกฟักชั่นที่เราต้องการจะทำงาน เช่น เรียก Loop ส่วน event ข้อ 3 คือเมื่อเสร็จฟังก์ชั่นแล้วจะให้ทำอะไร ส่วน event ข้อ 2 อ่านแล้วงงครับ ไม่รู้จะเอาไปใช้ตอนไหนเห็นตัวอย่างเขาใช้กับ progressbar แต่ผมก็ยังงงอยู่ดีว่า event ข้อ 2 เขาควรใช้ตอนไหน รบกวนพี่ๆที่มีความรู้เรื่องนี้อธิบายให้ผมเข้าใจด้วยครับ มีตัวอย่างด้วยจะดีมากเลยครับเพราะผมเป็นคนเข้าใจยากนิดนึง
ขอบคุณมากน่ะครับ
Date :
2011-04-23 10:54:40
By :
GhostLocal
รอผู้รู้ครับ
Date :
2011-04-26 15:27:06
By :
GhostLocal
Code (C#)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Allsync
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string _Jobpath = @"ManageJob.ini";
//ฟังก์ชั่นหาลำดับของ TabControl
public int findTabindex(string argTab)
{
for (int i = 0; i < tabAllJob.TabPages.Count; i++)
{
if (tabAllJob.TabPages[i].Text == argTab)
{
return i;
}
}
return -1;
}
private void Form1_Load(object sender, EventArgs e)
{
btnSync.Enabled = false;
btnStop.Enabled = false;
this.Text = " Allsync for Files";
toolStripProgressBar1.Visible = false;
if (File.Exists(_Jobpath))
{
string[] textjob = File.ReadAllLines(_Jobpath);
int len = textjob.Length;
foreach (string job in textjob)
{
if (job == "[ListJob]")
{
continue;
}
else
{
tabAllJob.TabPages.Add(job);
}
}
}
string TabName=tabAllJob.SelectedTab.Text;
Clini loadTextfile = new Clini();
txtSource.Text = loadTextfile.readini(1, TabName + "Setting");
txtDesti.Text = loadTextfile.readini(3, TabName + "Setting");
toolStripStatusLabel1.Text = "Ready";
}
private void btnSaveSetting_Click(object sender, EventArgs e)
{
Clini writertext = new Clini();
toolStripStatusLabel1.Text = writertext.writTotext(txtSource.Text,txtDesti.Text,tabAllJob.SelectedTab.Text+"Setting");
}
private void tabAllJob_SelectedIndexChanged_1(object sender, EventArgs e)
{
btnSync.Enabled = false;
btnStop.Enabled = false;
Clini readini = new Clini();
listViewSource.Items.Clear();
listViewDesti.Items.Clear();
txtSource.Text = readini.readini(1, tabAllJob.SelectedTab.Text + "Setting");
txtDesti.Text = readini.readini(3, tabAllJob.SelectedTab.Text + "Setting");
toolStripStatusLabel1.Text = "Ready";
}
private void manageJobToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 managejob = new Form2();
string returncbo = managejob.returncbo("Manage Job");
if (returncbo == ".Add" || returncbo == ".Delete")
{
return;
}
else
{
string[] splitreturn = returncbo.Split('.');
//เพิ่ม Tabpage
if (splitreturn[1] == "Add")
{
tabAllJob.TabPages.Add(splitreturn[0]);
tabAllJob.SelectTab(tabAllJob.TabPages.Count - 1);
}
//ลบ Tabpage
else if (splitreturn[1] == "Delete")
{
if (findTabindex(splitreturn[0]) != -1)
{
Clini deletefile = new Clini();
tabAllJob.TabPages.RemoveAt(findTabindex(splitreturn[0]));
toolStripStatusLabel1.Text=deletefile.deletText(splitreturn[0]);
}
}
if (returncbo == "")
{
return;
}
}
}
private void buttonSpecAny1_Click_1(object sender, EventArgs e)
{
Clini BrowseSource = new Clini();
FBDialogSource.Description = "Please select the source folder";
FBDialogSource.SelectedPath = BrowseSource.readini(1, tabAllJob.SelectedTab.Text + "Setting");
if (FBDialogSource.ShowDialog() == DialogResult.OK)
{
txtSource.Text = FBDialogSource.SelectedPath;
}
else
{
return;
}
}
private void buttonSpecAny2_Click_1(object sender, EventArgs e)
{
Clini BrowseDesti = new Clini();
FBDialogSource.Description = "Please select the Destination folder";
FBDialogSource.SelectedPath = BrowseDesti.readini(3, tabAllJob.SelectedTab.Text + "Setting");
if (FBDialogSource.ShowDialog() == DialogResult.OK)
{
txtDesti.Text = FBDialogSource.SelectedPath;
}
else
{
return;
}
}
//แสดงข้อมูล Source
public string[] getSource(string argSource)
{
string[] dir = Directory.GetDirectories(argSource);
return dir;
}
public void getfilesinSource(params string[] argfolder)
{
foreach (string file in argfolder)
{
string[] files = Directory.GetFiles(file);
foreach (string filesinfolder in files)
{
string datemodisource = Convert.ToString(File.GetLastWriteTime(filesinfolder));
ListViewItem livitm = listViewSource.Items.Add(filesinfolder, 0);
int idx = listViewSource.Items.IndexOf(livitm);
listViewSource.Items[idx].SubItems.Add(datemodisource);
Application.DoEvents();
}
string[] dir = getSource(file);
getfilesinSource(dir);
}
}
//แสดงข้อมูล Destination
public string[] getDesti(string argDesti)
{
string[] dir = Directory.GetDirectories(argDesti);
return dir;
}
public void getfilesinDesti(params string[] argfolder)
{
foreach (string file in argfolder)
{
string[] files = Directory.GetFiles(file);
foreach (string filesinfolder in files)
{
string datemodidesti = Convert.ToString(File.GetLastWriteTime(filesinfolder));
ListViewItem livitm = listViewDesti.Items.Add(filesinfolder, 0);
int idx = listViewDesti.Items.IndexOf(livitm);
listViewDesti.Items[idx].SubItems.Add(datemodidesti);
Application.DoEvents();
}
string[] dir = getDesti(file);
getfilesinDesti(dir);
}
}
private void btnAnalyze_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
toolStripStatusLabel1.Text = "Please wait...";
Application.DoEvents();
btnSync.Enabled = false;
btnStop.Enabled = false;
btnSaveSetting.Enabled = false;
listViewDesti.Items.Clear();
listViewSource.Items.Clear();
Clini readini = new Clini();
string sourcetext = readini.readini(1, tabAllJob.SelectedTab.Text + "Setting");
string destitext = readini.readini(3, tabAllJob.SelectedTab.Text + "Setting");
listViewSource.SmallImageList = imageList1;
listViewDesti.SmallImageList = imageList1;
//แสดงไฟล์ทั้งหมดใน Source
getfilesinSource(sourcetext);
getfilesinDesti(destitext);
toolStripStatusLabel1.Text = "Ready";
btnSync.Enabled = true;
btnStop.Enabled = true;
btnSaveSetting.Enabled = true;
Cursor.Current = Cursors.Default;
}
private void btnSync_Click(object sender, EventArgs e)
{
timer1.Interval = 1;
timer1.Start();
btnSync.Enabled = false;
btnAnalyze.Enabled = false;
btnSaveSetting.Enabled = false;
toolStripStatusLabel1.Text = "Please wait...";
Application.DoEvents();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (listViewDesti.Items.Count == 0)
{
ClAllsync syncCopy = new ClAllsync();
syncCopy.CopyFolder(txtSource.Text, txtDesti.Text);
}
else
{
ClAllsync newCopy = new ClAllsync();
newCopy.CopyNewFiles(txtSource.Text, txtDesti.Text);
for (int i = 0; i < listViewSource.Items.Count; i++)
{
string namefilesource = Path.GetFileName(listViewSource.Items[i].Text);
DateTime datename_s = File.GetLastWriteTime(listViewSource.Items[i].Text);
for (int j = i; i < listViewDesti.Items.Count; j++)
{
string namefiledest = Path.GetFileName(listViewDesti.Items[j].Text);
DateTime datename_d = File.GetLastWriteTime(listViewDesti.Items[j].Text);
if (namefilesource == namefiledest)
{
if (datename_s != datename_d)
{
File.Copy(listViewSource.Items[i].Text, listViewDesti.Items[j].Text, true);
Application.DoEvents();
}
else
{
break;
}
}
else
{
break;
}
break;
}
}
toolStripStatusLabel1.Text = "Synchronize successfully.";
timer1.Stop();
btnAnalyze.Enabled = true;
btnSync.Enabled = true;
btnSaveSetting.Enabled = true;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
timer1.Interval = 1;
toolStripStatusLabel1.Text = "Synchronize interrupt";
btnAnalyze.Enabled = true;
btnSync.Enabled = true;
btnSaveSetting.Enabled = true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
โค้ตข้างบนจะเขียนแบบมี BackgroundWorker อย่างไงหรอครับ รบกวนดูให้หน่อยครับ ขอบคุณครับ
Date :
2011-04-26 15:50:33
By :
GhostLocal
Code (VB.NET)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace Allsync
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string _Jobpath = @"ManageJob.ini";
private string _Tabtext;
public string tabtext
{
set { _Tabtext = value; }
get { return _Tabtext; }
}
//ฟังก์ชั่นหาลำดับของ TabControl
public int findTabindex(string argTab)
{
for (int i = 0; i < tabAllJob.TabPages.Count; i++)
{
if (tabAllJob.TabPages[i].Text == argTab)
{
return i;
}
}
return -1;
}
private void Form1_Load(object sender, EventArgs e)
{
btnSync.Enabled = false;
btnStop.Enabled = false;
this.Text = " Allsync for Files";
toolStripProgressBar1.Visible = false;
if (File.Exists(_Jobpath))
{
string[] textjob = File.ReadAllLines(_Jobpath);
int len = textjob.Length;
foreach (string job in textjob)
{
if (job == "[ListJob]")
{
continue;
}
else
{
tabAllJob.TabPages.Add(job);
}
}
}
string TabName=tabAllJob.SelectedTab.Text;
Clini loadTextfile = new Clini();
txtSource.Text = loadTextfile.readini(1, TabName + "Setting");
txtDesti.Text = loadTextfile.readini(3, TabName + "Setting");
toolStripStatusLabel1.Text = "Ready";
}
private void btnSaveSetting_Click(object sender, EventArgs e)
{
Clini writertext = new Clini();
toolStripStatusLabel1.Text = writertext.writTotext(txtSource.Text,txtDesti.Text,tabAllJob.SelectedTab.Text+"Setting");
}
private void tabAllJob_SelectedIndexChanged_1(object sender, EventArgs e)
{
btnSync.Enabled = false;
btnStop.Enabled = false;
Clini readini = new Clini();
listViewSource.Items.Clear();
listViewDesti.Items.Clear();
txtSource.Text = readini.readini(1, tabAllJob.SelectedTab.Text + "Setting");
txtDesti.Text = readini.readini(3, tabAllJob.SelectedTab.Text + "Setting");
toolStripStatusLabel1.Text = "Ready";
}
private void manageJobToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 managejob = new Form2();
string returncbo = managejob.returncbo("Manage Job");
if (returncbo == ".Add" || returncbo == ".Delete")
{
return;
}
else
{
string[] splitreturn = returncbo.Split('.');
//เพิ่ม Tabpage
if (splitreturn[1] == "Add")
{
tabAllJob.TabPages.Add(splitreturn[0]);
tabAllJob.SelectTab(tabAllJob.TabPages.Count - 1);
}
//ลบ Tabpage
else if (splitreturn[1] == "Delete")
{
if (findTabindex(splitreturn[0]) != -1)
{
Clini deletefile = new Clini();
tabAllJob.TabPages.RemoveAt(findTabindex(splitreturn[0]));
toolStripStatusLabel1.Text=deletefile.deletText(splitreturn[0]);
}
}
if (returncbo == "")
{
return;
}
}
}
private void buttonSpecAny1_Click_1(object sender, EventArgs e)
{
Clini BrowseSource = new Clini();
FBDialogSource.Description = "Please select the source folder";
FBDialogSource.SelectedPath = BrowseSource.readini(1, tabAllJob.SelectedTab.Text + "Setting");
if (FBDialogSource.ShowDialog() == DialogResult.OK)
{
txtSource.Text = FBDialogSource.SelectedPath;
}
else
{
return;
}
}
private void buttonSpecAny2_Click_1(object sender, EventArgs e)
{
Clini BrowseDesti = new Clini();
FBDialogSource.Description = "Please select the Destination folder";
FBDialogSource.SelectedPath = BrowseDesti.readini(3, tabAllJob.SelectedTab.Text + "Setting");
if (FBDialogSource.ShowDialog() == DialogResult.OK)
{
txtDesti.Text = FBDialogSource.SelectedPath;
}
else
{
return;
}
}
//แสดงข้อมูล Source
public string[] getSource(string argSource)
{
string[] dir = Directory.GetDirectories(argSource);
return dir;
}
public void getfilesinSource(params string[] argfolder)
{
foreach (string file in argfolder)
{
string[] files = Directory.GetFiles(file);
foreach (string filesinfolder in files)
{
string datemodisource = Convert.ToString(File.GetLastWriteTime(filesinfolder));
ListViewItem livitm = listViewSource.Items.Add(filesinfolder, 0); //error ตรงนี้อ่ะครับ
int idx = listViewSource.Items.IndexOf(livitm);
listViewSource.Items[idx].SubItems.Add(datemodisource);
//Application.DoEvents();
Thread.Sleep(1);
}
string[] dir = getSource(file);
getfilesinSource(dir);
Thread.Sleep(1);
}
}
//แสดงข้อมูล Destination
public string[] getDesti(string argDesti)
{
string[] dir = Directory.GetDirectories(argDesti);
return dir;
}
public void getfilesinDesti(params string[] argfolder)
{
foreach (string file in argfolder)
{
string[] files = Directory.GetFiles(file);
foreach (string filesinfolder in files)
{
string datemodidesti = Convert.ToString(File.GetLastWriteTime(filesinfolder));
ListViewItem livitm = listViewDesti.Items.Add(filesinfolder,0);//error ตรงนี้อ่ะครับ
int idx = listViewDesti.Items.IndexOf(livitm);
listViewDesti.Items[idx].SubItems.Add(datemodidesti);
Application.DoEvents();
}
string[] dir = getDesti(file);
getfilesinDesti(dir);
}
}
private void btnAnalyze_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
toolStripStatusLabel1.Text = "Please wait...";
Application.DoEvents();
btnSync.Enabled = false;
btnStop.Enabled = false;
btnSaveSetting.Enabled = false;
listViewDesti.Items.Clear();
listViewSource.Items.Clear();
tabtext = tabAllJob.SelectedTab.Text;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerReportsProgress = true;
listViewSource.SmallImageList = imageList1;
listViewDesti.SmallImageList = imageList1;
}
private void btnSync_Click(object sender, EventArgs e)
{
timer1.Interval = 1;
timer1.Start();
btnSync.Enabled = false;
btnAnalyze.Enabled = false;
btnSaveSetting.Enabled = false;
toolStripStatusLabel1.Text = "Please wait...";
Application.DoEvents();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (listViewDesti.Items.Count == 0)
{
ClAllsync syncCopy = new ClAllsync();
syncCopy.CopyFolder(txtSource.Text, txtDesti.Text);
}
else
{
ClAllsync newCopy = new ClAllsync();
newCopy.CopyNewFiles(txtSource.Text, txtDesti.Text);
for (int i = 0; i < listViewSource.Items.Count; i++)
{
string namefilesource = Path.GetFileName(listViewSource.Items[i].Text);
DateTime datename_s = File.GetLastWriteTime(listViewSource.Items[i].Text);
for (int j = i; i < listViewDesti.Items.Count; j++)
{
string namefiledest = Path.GetFileName(listViewDesti.Items[j].Text);
DateTime datename_d = File.GetLastWriteTime(listViewDesti.Items[j].Text);
if (namefilesource == namefiledest)
{
if (datename_s != datename_d)
{
File.Copy(listViewSource.Items[i].Text, listViewDesti.Items[j].Text, true);
Application.DoEvents();
}
else
{
break;
}
}
else
{
break;
}
break;
}
}
toolStripStatusLabel1.Text = "Synchronize successfully.";
timer1.Stop();
btnAnalyze.Enabled = true;
btnSync.Enabled = true;
btnSaveSetting.Enabled = true;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
timer1.Interval = 1;
toolStripStatusLabel1.Text = "Synchronize interrupt";
btnAnalyze.Enabled = true;
btnSync.Enabled = true;
btnSaveSetting.Enabled = true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Clini readini = new Clini();
string sourcetext = readini.readini(1, tabtext + "Setting");
string destitext = readini.readini(3, tabtext + "Setting");
e.Result = sourcetext;
e.Result = destitext;
//แสดงไฟล์ทั้งหมดใน Source
getfilesinSource(sourcetext);
getfilesinDesti(destitext);
toolStripStatusLabel1.Text = "Ready";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnSync.Enabled = true;
btnStop.Enabled = true;
btnSaveSetting.Enabled = true;
Cursor.Current = Cursors.Default;
}
}
}
ลองทำแล้วครับ แต่มันติดตรง listView และก็ขึ้น error ว่า
Cross-thread operation not valid: Control 'listViewSource' accessed from a thread other than the thread it was created on.
Date :
2011-04-26 16:35:40
By :
GhostLocal
http://www.greatfriends.biz/webboards/msg.asp?b=SURREALIST&id=124393&sw=Task%20Parallel
ทำไมผมเข้าได้ปกติ ???
งั้นเอาตัวอย่าง background worker ไปดูเล่นละกัน
Code (C#)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace bkwTest2
{
public partial class Form1 : Form
{
private BackgroundWorker _bkw = new BackgroundWorker();
private ProgressBar _pgb1 = new ProgressBar();
public Form1 ()
{
InitializeComponent();
_pgb1.Dock = DockStyle.Bottom;
_pgb1.Height = 10;
_pgb1.Maximum = 100;
_pgb1.Parent = this;
_bkw.DoWork += new DoWorkEventHandler( bkw_DoWork );
_bkw.ProgressChanged += new ProgressChangedEventHandler( bkw_ProgressChanged );
_bkw.RunWorkerCompleted += new RunWorkerCompletedEventHandler( bkw_RunWorkerCompleted );
_bkw.WorkerReportsProgress = true; // <-- ไม่งั้นจะ error ตรง ReportProgress
_bkw.RunWorkerAsync();
}
void bkw_RunWorkerCompleted ( object sender , RunWorkerCompletedEventArgs e )
{
MessageBox.Show( " เสร็จแล้วจ้า !!! " );
}
void bkw_ProgressChanged ( object sender , ProgressChangedEventArgs e )
{
_pgb1.Value = e.ProgressPercentage;
}
void bkw_DoWork ( object sender , DoWorkEventArgs e )
{
for( int i = 0 ; i <= 20 ; ++i )
{
System.Threading.Thread.Sleep( 500 );// <--หน่วงเวลา 0.5 วิ เด๋วเร็วเกิน ดูไม่ทัน
_bkw.ReportProgress( i * 5 ); // <--ส่งค่าไป Event ProgressChanged
if( this.InvokeRequired ) // <--จำเทมเพลตนี้ไห้ดี จะแก้ property control ใน thread อื่น ต้องเขียนแบบนี้
{
this.Invoke( new MethodInvoker( delegate()
{
this.Text = i.ToString();// <-- กำหนดค่าให้ control ตรงนี้
}
) );
}
else
{
this.Text = i.ToString();
}
}
}
}
}
Date :
2011-04-26 18:30:32
By :
Programmer Of Persia
ขอบคุณครับเดี๋ยวเอาไปศึกษา
Date :
2011-04-27 08:54:16
By :
GhostLocal
ตอนนี้ผมพอเ้ข้าใจแล้วครับ ผมก็เลยไปเขียนโค้ตแบบง่ายๆก่อน โดยใช้ listView แต่ว่าทำไมมันออกมาแบบนี้ก็ไม่รู้ใน Directory ที่ผมกำหนดมันมีไฟล์อยู่ 3 ไฟล์แต่พอรันโปรแกรมออกมา มันแสดงไฟล์ใน listView ออกมาเป็น 3 ชุดอ่ะครับ
Code (C#)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
namespace TestBGW
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private string pathpic = @"C:\Documents and Settings\Administrator\My Documents\My Pictures\Car";
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bwk = sender as BackgroundWorker;
int len = Path.GetFileName(pathpic).Length;
for (int i = 0; i < len; i++)
{
bwk.ReportProgress((i*100)/(len-1));
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
ListViewItem LvItm;
string[] files = Directory.GetFiles(pathpic);
foreach (string file in files)
{
LvItm = listView1.Items.Add(file);
int idx = listView1.Items.IndexOf(LvItm);
string modified = Convert.ToString(File.GetLastWriteTime(file));
listView1.Items[idx].SubItems.Add(modified);
}
progressBar1.Value = e.ProgressPercentage;
this.Text = e.ProgressPercentage.ToString() + "%";
}
private void button1_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("เสร็จแล้วครับ", "Message Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
ตอนรันโปรแกรม
แต่ใน Directory ทีำกำหนดมี 3 ไฟล์
รบกวนชี้แนะด้วยน่ะครับ
Date :
2011-04-27 11:35:21
By :
GhostLocal
ลองศึกษาเรื่อง delegate, thread safe ดูนะครับ
ผมว่า code ที่ run ได้ควรเป็นแบบนี้ ลองปรับแต่งให้สมบูรณ์นะครับ
Code (C#)
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
MessageBox.Show("Cancel", "Message Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
else if(e.Error != null)
MessageBox.Show(e.Error.Message, "Message Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("เสร็จแล้วครับ", "Message Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button1_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
progressBar1.Value = 0;
progressBar1.Maximum = Directory.GetFiles(pathpic).Count();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
decimal percentCompleted = ((progressBar1.Value * 100) / (decimal)progressBar1.Maximum);
this.Text = percentCompleted.ToString("N2")+"%";
}
delegate void AddListViewItemCallback(object item);
private void AddListViewItem( object item ) {
if (this.listView1.InvokeRequired)
{
AddListViewItemCallback cb = new AddListViewItemCallback(AddListViewItem);
this.Invoke(cb, new object[] { item });
}
else
{
ListViewItem newItem = (ListViewItem)item;
listView1.Items.Add(newItem);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string[] files = Directory.GetFiles(pathpic);
int i = 0;
foreach (string file in files)
{
string modified = Convert.ToString(File.GetLastWriteTime(file));
ListViewItem newItem = new ListViewItem(file) ;
newItem.SubItems.Add(modified);
AddListViewItem(newItem);
i += 1;
backgroundWorker1.ReportProgress(i);
}
}
Date :
2011-04-27 13:05:50
By :
mi16
สุดยอดไปเลยครับคุณ mi16 เด๊่ยวต้องไปศึกษาdelegate บ้างซะแล้ว
Date :
2011-04-27 14:18:06
By :
GhostLocal
Load balance : Server 00