Task.Run
private void button1_Click(object sender, EventArgs e)
{
int first=0, second = 0;
var taskList = new List<Task>();
taskList.Add(Task.Run(() =>
{
first = PrintOne(10,20);
}));
taskList.Add(Task.Run(() =>
{
second = PrintTwo(30,40);
}));
Task.WaitAll(taskList.ToArray());
MessageBox.Show((first+second).ToString());
}
int PrintOne(int i, int k)
{
Thread.Sleep(5000);
return i + k;
}
int PrintTwo(int i, int k)
{
Thread.Sleep(5000);
return i + k;
}
Backgroud workers
BackgroundWorker m_oWorker;
private void button2_Click(object sender, EventArgs e)
{
m_oWorker = new BackgroundWorker();
m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);
m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
m_oWorker.WorkerReportsProgress = true;
m_oWorker.WorkerSupportsCancellation = true;
m_oWorker.RunWorkerAsync();
}
private string a = "";
void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(5000);
a = "Done :)";
}
void m_oWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(a);
}
Multiple tasks
var task = new List<Task>();
task.Add(Task.Run(() =>
{
EventData();
}));
task.Add(Task.Run(() =>
{
if (!string.IsNullOrWhiteSpace(userid))
{
SubAccountParticipants();
}
}));
Task.WaitAll(task.ToArray());
Threading file copy
void Copy(object o) {
Console.WriteLine(o.ToString());
Thread.Sleep(1000);
}
bool IsStop = false;
int count = 0;
//start
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("start coping");
IsStop = false;
List<string> lst = new List<string>();
for (int i = 0; i < 10; i++)
{
lst.Add("files " + i);
}
Thread t = new Thread(new ThreadStart(() =>
{
while (count < lst.Count && !IsStop)
{
Copy(lst[count]);
count++;
}
}));
t.Start();
t.Join();
Console.WriteLine("stop coping");
}
//stop
private void button2_Click(object sender, EventArgs e)
{
IsStop = true;
}
Task With List
var lst = new List<string>(2000); var t1 = Task.Run(() => { for (int i = 0; i < 500; i++) { lst.Add($"thread 1 - {i}"); Thread.Sleep(100); } }); var t2 = Task.Run(() => { for (int i = 0; i < 500; i++) { lst.Add($"thread 2 - {i}"); Thread.Sleep(100); } }); Task.WaitAll(t1, t2); Console.WriteLine("End"); Console.Read();
No comments:
Post a Comment