# data[].attributes.headline
โพสต์ที่ได้รับการช่วยเหลือและสำเร็จแล้ว (สีเขียว)

# data[].attributes.subject
โพสต์ที่ได้รับการช่วยเหลือและสำเร็จแล้ว (สีเขียว)

# data[].attributes.body
โพสต์ที่ได้รับการช่วยเหลือแล้ว และสำเร็จตามความต้องการ จาก TA จะย้ายมาอยู่ทางซ้ายของโพสต์ ที่มี Helpdesk icon และจะปรับพื้นหลังเป็นสีเขียว

# data[].attributes.headline
โพสต์ปัญหาที่ต้องการความช่วยเหลือพร้อมรหัส  AnyDesk

# data[].attributes.subject
โพสต์ปัญหาที่ต้องการความช่วยเหลือพร้อมรหัส  AnyDesk

# data[].attributes.body
1. เขียนคำอธิบายปัญหา
2. แนบรูปหน้าจอประกอบ

# data[].attributes.headline
โพสต์ปัญหาใหม่ (สีขาว)

# data[].attributes.subject
โพสต์ปัญหาใหม่ (สีขาว)

# data[].attributes.body
โพสต์ใหม่ที่ยังไม่ได้รับการช่วยเหลือจาก TA จะอยู่ทางขวาของ Helpdesk icon โพสต์และจะมีพื้นหลังสีขาว

# data[].attributes.headline
โพสต์ข้อมูลแนะนำ (สีฟ้า)

# data[].attributes.subject
โพสต์ข้อมูลแนะนำ (สีฟ้า)

# data[].attributes.body
สีพื้นหลังโพสต์จะความหมายดังนี้
สีขาว - ขอความช่วยเหลือใหม่
สีเหลือง - กำลังเข้าช่วยเหลือ
สีเขียว - ช่วยเหลือสำเร็จแล้ว
สีฟ้า - ข้อมูลทั่วไปสำหรับทุกคน
ขอให้ทุกคนเลือกสีตามที่กำหนด

# data[].attributes.headline
โพสต์กำลังดำเนินการ (สีเหลือง)

# data[].attributes.subject
โพสต์กำลังดำเนินการ (สีเหลือง)

# data[].attributes.body
TA กำลังให้คำแนะนำและกำลังดำเนินการแก้ปัญหา

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prog2017_000_your_first_csharp
{
class Program
{
public const int arr_sz = 10;
static void Main(string[] args)
{
int[] a = new int[arr_sz];
int[] b = new int[arr_sz];
int[] c = new int[arr_sz];

int i;

//----initial value in a
for (i = 0; i < arr_sz; i++)
{
a[i] = i + 1;
b[i] = i * 10;
Console.WriteLine("a[{0} = {1}\t\tb[{0} = {2}", i, a[i], b[i]);
}

//----using for loop
for (i = 0; i < arr_sz; i++)
{
c[i] = a[i] + b[i];
Console.WriteLine("c[{0}]={1}", i, c[i]);
}

Console.ReadKey();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace prog2017_001_first_parallel_loop
{
class Program
{
static void Main(string[] args)
{
int x;
Console.WriteLine("Using conventional C# For Loop \n");
for (x = 0; x <= 20; x++)
{
Console.WriteLine("x = {0}, thread = {1}",
x, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}

Console.WriteLine("------------------------------------------------------");
Console.WriteLine("\nUsing Parallel.For \n");
Parallel.For(0, 20, i =>
{
Console.WriteLine("i = {0}, thread = {1}", i,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
});

for (int i = 1; i < 12; i++)
Console.WriteLine("{0}. {0}*{0}={1}", i, i * i);

Console.ReadLine();

}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace prog2017_002_of_LMS_add_array1
{
class Program
{
public const int arr_sz = 70000000;
static void Main(string[] args)
{
Stopwatch myStopWatch1 = new Stopwatch();
Stopwatch myStopWatch2 = new Stopwatch();
long exe_time_for, exe_time_parallel_for;

int[] a = new int[arr_sz];
int[] b = new int[arr_sz];
int[] c = new int[arr_sz];

int i;

//----initial value in a
for (i=0;i<arr_sz;i++)
{
a[i] = i + 1;
b[i] = i * 10;
}

myStopWatch1.Start();
//----using for loop
for (i=0;i<arr_sz;i++)
{
c[i] = a[i] + b[i];
//    Console.WriteLine("c[{0}]={1}", i, c[i]);
}
myStopWatch1.Stop();
exe_time_for = myStopWatch1.ElapsedMilliseconds;

//Console.ReadKey();

myStopWatch2.Start();
Parallel.For(0, arr_sz, x=>
{
c[x] = a[x] + b[x];
//    Console.WriteLine("thread id= {0},  c[{1}]={2}",Thread.CurrentThread.ManagedThreadId, x, c[x]);
});
myStopWatch2.Stop();
exe_time_parallel_for = myStopWatch2.ElapsedMilliseconds;

Console.WriteLine("Execution time of normal for = {0}", exe_time_for);
Console.WriteLine("Execution time of parallel for  = {0}", exe_time_parallel_for);

Console.ReadKey();
}
}
}

# data[].attributes.body
No input

# data[].attributes.headline
วาดไดอะแกรมความเข้าใจของ  TAS ของคุณ

# data[].attributes.subject
วาดไดอะแกรมความเข้าใจของ  TAS ของคุณ

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//--see http://www.dotnetcurry.com/showarticle.aspx?ID=491

namespace _010_parallel_task_question_prove
{
class Program
{
static void Main(string[] args)
{

//---------------------------------------------------------------------------------------------------------------
//---approach 1: Use the constructor of the Task(Of TResult) class to initialize the task but execute it later
//---------------------------------------------------------------------------------------------------------------
/*
// Create the Tasks
Task<int>       t1 = new Task<int>(GenerateNumbers);
Task<string>    t2 = new Task<string>(PrintCharacters);
Task<int>       t3 = new Task<int>(PrintArray);
// Start the tasks
t1.Start();
t2.Start();
t3.Start();
//Print Return Value
Console.WriteLine("Numbers generated till {0}", t1.Result);
Console.WriteLine("Original String {0}", t2.Result);
Console.WriteLine("Array Count {0}", t3.Result);
Console.ReadLine();
*/

//---------------------------------------------------------------------------------------------------------------
//---approach 2: using Task<>.Factory.StartNew() to initialize and execute the task at the same time
//---------------------------------------------------------------------------------------------------------------
// Create and execute the Tasks
var t1 = Task<int>.Factory.StartNew(() => GenerateNumbers());
var t2 = Task<string>.Factory.StartNew(() => PrintCharacters());
var t3 = Task<int>.Factory.StartNew(() => PrintArray());

//Print Return Value
Console.WriteLine("Array Count {0}", t3.Result);
Console.WriteLine("Original String {0}", t2.Result);
Console.WriteLine("Numbers generated till {0}", t1.Result);
Console.ReadLine();
}

static int GenerateNumbers()
{
int i;
for (i = 0; i < 7; i++)
{
Console.WriteLine("Method1 - Number: {0}", i);
Thread.Sleep(1000);
}
return i;
}

static string PrintCharacters()
{
string str = "dotnet";
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine("Method2 - Character: {0}", str[i]);
Thread.Sleep(100);
}
return str;
}

static int PrintArray()
{
int[] arr = { 1, 2, 3, 4, 5 };
foreach (int i in arr)
{
Console.WriteLine("Method3 - Array: {0}", i);
Thread.Sleep(10);
}
return arr.Count();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _001_try_parallel_loop1st
{
class Program
{
static void Main(string[] args)
{
int x;
Console.WriteLine("Using conventional C# For Loop \n");
for (x = 0; x <= 20; x++)
{
Console.WriteLine("x = {0}, thread = {1}",
x , Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}

Console.WriteLine("------------------------------------------------------");
Console.WriteLine("\nUsing Parallel.For \n");
Parallel.For(0, 20, i =>
{
Console.WriteLine("i = {0}, thread = {1}", i,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
});

Console.ReadLine();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

//---see http://stackoverflow.com/questions/2774170/parallel-for-update-variable-outside-of-loop to overcome the problem
//---see the corrected version in 013_parallel_loop_racing_corrected1   method1
//---                       and   014_parallel_loop_racing_corrected2   method2

namespace _011_parallel_loop_racing_condition1
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[1000];
int i, sum = 0;

for (i = 0; i < 1000; i++)
arr[i] = i;

//---------------------------------------------------------------------------------
//---sequential
//---------------------------------------------------------------------------------
sum = 0;
for (i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
Console.WriteLine("========================================\nSequential Program");
Console.WriteLine("the result of 1+2+...+999 = {0}", sum);
Console.WriteLine("========================================\n\n\n");

//---------------------------------------------------------------------------------
//---parallel
//---------------------------------------------------------------------------------
sum = 0;
Parallel.For(0, arr.Length, j =>
{
sum += arr[j];
});
Console.WriteLine("========================================\nParallel Program");
Console.WriteLine("the result of 1+2+...+999 = {0}", sum);
Console.WriteLine("========================================");

Console.ReadLine();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

//---see http://stackoverflow.com/questions/2774170/parallel-for-update-variable-outside-of-loop for error corrections
//--- the problem of parallel aggregation

namespace _012_parallel_loop_racing_condition2
{
class Program
{
static void Main(string[] args)
{
const int data_size = 5000000;
int[] data = new int[data_size];
int i;
double result_serial, result_parallel;
result_serial = 0.0;
result_parallel = 0.0;

//---initial values in the array
for (i = 0; i < data.Length; i++)
data[i] = i * i;

Stopwatch stopWatch = new Stopwatch();
long ex_time_serial, ex_time_parallel;

//---------------------------------------------------------------------------------
//---sequential
//---------------------------------------------------------------------------------
stopWatch.Start();
for (i = 0; i < data.Length; i++)
{
result_serial += ((Math.Sin((double)data[i]) - Math.Cos((double)data[i])) /
(Math.Sin((double)data[i]) + Math.Cos((double)data[i])));
}
stopWatch.Stop();
ex_time_serial = stopWatch.ElapsedMilliseconds;
Console.WriteLine("========================================\nSequential Program");
Console.WriteLine("the result = {0}", result_serial);
Console.WriteLine("Execution time = {0}", ex_time_serial);
Console.WriteLine("========================================");

//---------------------------------------------------------------------------------
//---parallel
//---------------------------------------------------------------------------------
object lockObject = new object();
stopWatch.Reset();
stopWatch.Start();
Parallel.ForEach(
// The values to be aggregated
data,

// The local initial partial result
() => 0.0d,

// The loop body
(x, loopState, partialResult) =>
{
double r_sin, r_cos;
r_sin = Math.Sin((double)x);
r_cos = Math.Cos((double)x);
//local_result += (r_sin - r_cos) / (r_cos + r_sin);

return (r_sin - r_cos) / (r_cos + r_sin) + partialResult;
},

// The final step of each local context
(localPartialSum) =>
{
// Enforce serial access to single, shared result
lock (lockObject)
{
result_parallel += localPartialSum;
}
});
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("====================================================================");
Console.WriteLine("Parallel Program using Parallel-aggregation pattern");
Console.WriteLine("the result = {0}", result_parallel);
Console.WriteLine("Execution time = {0}", ex_time_parallel);
Console.WriteLine("====================================================================");

Console.ReadLine();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

//---see http://stackoverflow.com/questions/2774170/parallel-for-update-variable-outside-of-loop
//---correct the problem of 011_parallel_loop_racing_condition1 with Interlocked.Add

namespace _013_parallel_loop_racing_corrected1
{
class Program
{
static void Main(string[] args)
{
const int a_size = 1000000;
int[] arr = new int[a_size];
int i, sum = 0;
Stopwatch stopWatch = new Stopwatch();
long ex_time_serial, ex_time_parallel;

for (i = 0; i < a_size; i++)
arr[i] = i;

//---------------------------------------------------------------------------------
//---sequential
//---------------------------------------------------------------------------------
sum = 0;
stopWatch.Start();
for (i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
stopWatch.Stop();
ex_time_serial = stopWatch.ElapsedMilliseconds;
Console.WriteLine("========================================\nSequential Program");
Console.WriteLine("the result of 1+2+...+999999 = {0}", sum);
Console.WriteLine("processing time = {0}", ex_time_serial);
Console.WriteLine("========================================\n\n\n");

//---------------------------------------------------------------------------------
//---parallel
//---------------------------------------------------------------------------------
sum = 0;
stopWatch.Start();
Parallel.For(0, arr.Length, j =>
{
Interlocked.Add(ref sum, arr[j]);
//sum += arr[j];
});
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("========================================\nParallel Program");
Console.WriteLine("the result of 1+2+...+999999 = {0}", sum);
Console.WriteLine("processing time = {0}", ex_time_parallel);
Console.WriteLine("========================================");

Console.ReadLine();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

//---see http://stackoverflow.com/questions/2774170/parallel-for-update-variable-outside-of-loop
//---see http://msdn.microsoft.com/en-us/library/dd460703.aspx

namespace _014_parallel_loop_racing_corrected2
{
class Program
{
static void Main(string[] args)
{
//ParallelOptions options = new ParallelOptions();
//options.MaxDegreeOfParallelism = 2;

const int a_size = 100000000;
int[] arr = new int[a_size];
int i;
long sum = 0;

Stopwatch stopWatch = new Stopwatch();
long ex_time_serial, ex_time_parallel;

for (i = 0; i < a_size; i++)
arr[i] = i;

//---------------------------------------------------------------------------------
//---sequential
//---------------------------------------------------------------------------------

stopWatch.Reset();
stopWatch.Start();
sum = 0;
for (i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
stopWatch.Stop();
ex_time_serial = stopWatch.ElapsedMilliseconds;
Console.WriteLine("======================================================================\nSequential Program");
Console.WriteLine("the result of 1+2+...+{1} = {0}", sum,a_size-1);
Console.WriteLine("processing time = {0}", ex_time_serial);
Console.WriteLine("======================================================================\n\n\n");

//---------------------------------------------------------------------------------
//---parallel using thread-local variables
//---------------------------------------------------------------------------------
stopWatch.Reset();
stopWatch.Start();
sum = 0;
// Use type parameter to make subtotal a long, not an int
Parallel.For<long>(0, arr.Length, () => 0, (j, loop, partial_sum) =>
{
partial_sum += arr[j];
return partial_sum;
},
(x) => Interlocked.Add(ref sum, x)
);
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("=================================================================\nParallel Program");
Console.WriteLine("the result of 1+2+...+{1} = {0}", sum, a_size - 1);
Console.WriteLine("processing time using thread local variable= {0}", ex_time_parallel);
Console.WriteLine("=================================================================\n\n\n");

//---------------------------------------------------------------------------------
//---parallel using parallel aggregation
//---------------------------------------------------------------------------------
object lockObject = new object();
stopWatch.Reset();
stopWatch.Start();
sum = 0;
Parallel.ForEach<int,long>(
// The values to be aggregated
arr,

// The local initial partial result
() => 0,

// The loop body
(xx, loopState, partialResult) =>
{
return xx + partialResult;
},

// The final step of each local context
(localPartialSum) =>
{
// Enforce serial access to single, shared result
lock (lockObject)
{
sum += localPartialSum;
}
});
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("=================================================================\nParallel Program");
Console.WriteLine("the result of 1+2+...+{1} = {0}", sum, a_size - 1);
Console.WriteLine("processing time using parallel aggregation= {0}", ex_time_parallel);
Console.WriteLine("=================================================================\n\n\n");

//---------------------------------------------------------------------------------
//---parallel using Interlocked.add
//---------------------------------------------------------------------------------
stopWatch.Reset();
stopWatch.Start();
sum = 0;
Parallel.For (0, arr.Length, j =>
{
Interlocked.Add(ref sum, arr[j]);
}
);
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("=================================================================\nParallel Program");
Console.WriteLine("the result of 1+2+...+{1} = {0}", sum, a_size - 1);
Console.WriteLine("processing time using Interlocked.Add = {0}", ex_time_parallel);
Console.WriteLine("=================================================================\n\n\n");

Console.ReadLine();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//--see http://www.dotnetcurry.com/showarticle.aspx?ID=491

namespace _015_parallel_task_wait_ALL
{
class Program
{
static void Main(string[] args)
{

//---------------------------------------------------------------------------------------------------------------
//---approach 1: Use the constructor of the Task(Of TResult) class to initialize the task but execute it later
//---------------------------------------------------------------------------------------------------------------
/*
// Create the Tasks
Task<int>       t1 = new Task<int>(GenerateNumbers);
Task<string>    t2 = new Task<string>(PrintCharacters);
Task<int>       t3 = new Task<int>(PrintArray);
// Start the tasks
t1.Start();
t2.Start();
t3.Start();
//Print Return Value
Console.WriteLine("Numbers generated till {0}", t1.Result);
Console.WriteLine("Original String {0}", t2.Result);
Console.WriteLine("Array Count {0}", t3.Result);
Console.ReadLine();
*/

//---------------------------------------------------------------------------------------------------------------
//---approach 2: using Task<>.Factory.StartNew() to initialize and execute the task at the same time
//---------------------------------------------------------------------------------------------------------------
// Create and execute the Tasks

var t1 = Task<int>.Factory.StartNew(() => GenerateNumbers());
var t2 = Task<string>.Factory.StartNew(() => PrintCharacters());
var t3 = Task<int>.Factory.StartNew(() => PrintArray());

// Task.WaitAny(t1, t2, t3);
//Print Return Value
for (int i = 0; i < 10; i++)
{
Thread.Sleep(2);
Console.WriteLine("main task\n");
}
Console.WriteLine("<result t3>Array Count {0}", t3.Result);
Console.WriteLine("<result t2>Original String {0}", t2.Result);
Console.WriteLine("<result t1>Numbers generated till {0}", t1.Result);
Console.ReadLine();
}

static int GenerateNumbers()
{
int i;
for (i = 0; i < 7; i++)
{
Console.WriteLine("Method1 - Number: {0}", i);
Thread.Sleep(1000);
}
return i;
}

static string PrintCharacters()
{
string str = "dotnet";
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine("Method2 - Character: {0}", str[i]);
Thread.Sleep(100);
}
return str;
}

static int PrintArray()
{
int[] arr = { 1, 2, 3, 4, 5 };
foreach (int i in arr)
{
Console.WriteLine("Method3 - Array: {0}", i);
Thread.Sleep(10);
}
return arr.Count();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//--see http://www.dotnetcurry.com/showarticle.aspx?ID=491

namespace _016_parallel_task_wait_all2
{
class Program
{
static void Main(string[] args)
{

//---------------------------------------------------------------------------------------------------------------
//---approach 1: Use the constructor of the Task(Of TResult) class to initialize the task but execute it later
//---------------------------------------------------------------------------------------------------------------
/*
// Create the Tasks
Task<int>       t1 = new Task<int>(GenerateNumbers);
Task<string>    t2 = new Task<string>(PrintCharacters);
Task<int>       t3 = new Task<int>(PrintArray);
// Start the tasks
t1.Start();
t2.Start();
t3.Start();
//Print Return Value
Console.WriteLine("Numbers generated till {0}", t1.Result);
Console.WriteLine("Original String {0}", t2.Result);
Console.WriteLine("Array Count {0}", t3.Result);
Console.ReadLine();
*/

//---------------------------------------------------------------------------------------------------------------
//---approach 2: using Task<>.Factory.StartNew() to initialize and execute the task at the same time
//---------------------------------------------------------------------------------------------------------------
// Create and execute the Tasks
var t1 = Task<int>.Factory.StartNew(() => GenerateNumbers());
var t2 = Task<string>.Factory.StartNew(() => PrintCharacters());
var t3 = Task<int>.Factory.StartNew(() => PrintArray());

for (int x = 0; x < 100; x++)
Console.WriteLine("{0} ", x);

// Task.WaitAll(t1, t2, t3);
//Print Return Value
Console.WriteLine("<result t3>Array Count {0}", t3.Result);
Console.WriteLine("<result t2>Original String {0}", t2.Result);
Console.WriteLine("<result t1>Numbers generated till {0}", t1.Result);
Console.ReadLine();
}

static int GenerateNumbers()
{
int i;
for (i = 0; i < 7; i++)
{
Console.WriteLine("Method1 - Number: {0}", i);
Thread.Sleep(3000);
}
return i;
}

static string PrintCharacters()
{
string str = "dotnet";
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine("Method2 - Character: {0}", str[i]);
Thread.Sleep(300);
}
return str;
}

static int PrintArray()
{
int[] arr = { 1, 2, 3, 4, 5 };
foreach (int i in arr)
{
Console.WriteLine("Method3 - Array: {0}", i);
Thread.Sleep(30);
}
return arr.Count();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//--see http://www.dotnetcurry.com/showarticle.aspx?ID=491

namespace _017_parallel_task_waitAny1
{
class Program
{
static void Main(string[] args)
{

//---------------------------------------------------------------------------------------------------------------
//---approach 1: Use the constructor of the Task(Of TResult) class to initialize the task but execute it later
//---------------------------------------------------------------------------------------------------------------
/*
// Create the Tasks
Task<int>       t1 = new Task<int>(GenerateNumbers);
Task<string>    t2 = new Task<string>(PrintCharacters);
Task<int>       t3 = new Task<int>(PrintArray);
// Start the tasks
t1.Start();
t2.Start();
t3.Start();
//Print Return Value
Console.WriteLine("Numbers generated till {0}", t1.Result);
Console.WriteLine("Original String {0}", t2.Result);
Console.WriteLine("Array Count {0}", t3.Result);
Console.ReadLine();
*/

//---------------------------------------------------------------------------------------------------------------
//---approach 2: using Task<>.Factory.StartNew() to initialize and execute the task at the same time
//---------------------------------------------------------------------------------------------------------------
// Create and execute the Tasks
var t1 = Task<int>.Factory.StartNew(()      => GenerateNumbers());
var t2 = Task<string>.Factory.StartNew(()   => PrintCharacters());
var t3 = Task<int>.Factory.StartNew(()      => PrintArray());

Task.WaitAny(t1, t2, t3);
Console.WriteLine("After one fastest has been completed");

Console.WriteLine("<result t3>Array Count {0}", t3.Result);
Console.WriteLine("<result t2>Original String {0}", t2.Result);
Console.WriteLine("<result t1>Numbers generated till {0}", t1.Result);
Console.ReadLine();
}

static int GenerateNumbers()
{
int i;
for (i = 0; i < 7; i++)
{
Console.WriteLine("Method1 - Number: {0}", i);
Thread.Sleep(1000);
}
return i;
}

static string PrintCharacters()
{
string str = "dotnet";
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine("Method2 - Character: {0}", str[i]);
Thread.Sleep(100);
}
return str;
}

static int PrintArray()
{
int[] arr = { 1, 2, 3, 4, 5 };
foreach (int i in arr)
{
Console.WriteLine("Method3 - Array: {0}", i);
Thread.Sleep(10);
}
return arr.Count();
}
}
}

# data[].attributes.headline
ส่ง  Spec เครื่องของคุณ

# data[].attributes.subject
ส่ง  Spec เครื่องของคุณ

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace try_image_bitmap01
{
class Program
{
static void Main(string[] args)
{
}

public void SetPixel_Example()
{

// Create a Bitmap object from a file.
Bitmap myBitmap = new Bitmap("Grapes.jpg");

// Draw myBitmap to the screen.
e.Graphics.DrawImage(myBitmap, 0, 0, myBitmap.Width,
myBitmap.Height);

// Set each pixel in myBitmap to black.
for (int Xcount = 0; Xcount < myBitmap.Width; Xcount++)
{
for (int Ycount = 0; Ycount < myBitmap.Height; Ycount++)
{
myBitmap.SetPixel(Xcount, Ycount, Color.Black);
}
}

// Draw myBitmap to the screen again.
e.Graphics.DrawImage(myBitmap, myBitmap.Width, 0,
myBitmap.Width, myBitmap.Height);
}
}
}

# data[].attributes.body
//===============================================================================
// Microsoft patterns & practices
// Parallel Programming Guide
//===============================================================================
// Copyright © Microsoft Corporation.  All rights reserved.
// This code released under the terms of the
// Microsoft patterns & practices license (http://parallelpatterns.codeplex.com/license).
//===============================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Practices.ParallelGuideSamples.Utilities;
using System.IO;

namespace _018_parallel_task_image_blender
{
class Program
{
static void SetToGray(Bitmap source, Bitmap layer)
{
source.CopyPixels(layer);
layer.SetGray();
layer.SetAlpha(128);
}

static void Rotate(Bitmap source, Bitmap layer)
{
source.CopyPixels(layer);
layer.RotateFlip(RotateFlipType.Rotate90FlipNone);
layer.SetAlpha(128);
}

// Alpha blend: call DrawImage on each layer in turn
static void Blend(Bitmap layer1, Bitmap layer2, Graphics blender)
{
blender.DrawImage(layer1, 0, 0);
blender.DrawImage(layer2, 0, 0);
}

static int SeqentialImageProcessing(Bitmap source1, Bitmap source2,
Bitmap layer1, Bitmap layer2, Graphics blender)
{
SetToGray(source1, layer1);
Rotate(source2, layer2);
Blend(layer1, layer2, blender);
return source1.Width;
}

static int ParallelTaskImageProcessing(Bitmap source1, Bitmap source2,
Bitmap layer1, Bitmap layer2, Graphics blender)
{
Task toGray = Task.Factory.StartNew(() => SetToGray(source1, layer1));
Task rotate = Task.Factory.StartNew(() => Rotate(source2, layer2));
Task.WaitAll(toGray, rotate);
Blend(layer1, layer2, blender);
return source1.Width;
}

static int ParallelInvokeImageProcessing(Bitmap source1, Bitmap source2,
Bitmap layer1, Bitmap layer2, Graphics blender)
{
Parallel.Invoke(
() => SetToGray(source1, layer1),
() => Rotate(source2, layer2));
Blend(layer1, layer2, blender);
return source1.Width;
}

/// <summary>
/// Parallel tasks sample
/// Command line arguments are:
///  image source directory, default: current directory
///  first source image file, default: flowers.jpg
///  second source image file, default: dog.jpg
///  blended image destination directory, default: current directory
/// If any of the directories or files do not exist, the program exits without results.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Image Blender Sample\n");
#if DEBUG
Console.WriteLine("For most accurate timing results, use Release build.\n");
#endif
string sourceDir = Directory.GetCurrentDirectory();
string file1 = "flowers.jpg"; // don't rotate
string file2 = "dog.jpg";     // don't set to gray
string destDir = Directory.GetCurrentDirectory();

if (args.Length > 0) sourceDir = args[0];
if (args.Length > 1) file1 = args[1];
if (args.Length > 2) file2 = args[2];
if (args.Length > 3) destDir = args[3];

string path1 = Path.Combine(sourceDir, file1);
string path2 = Path.Combine(sourceDir, file2);

SampleUtilities.CheckDirectoryExists(sourceDir);
SampleUtilities.CheckFileExists(path1);
SampleUtilities.CheckFileExists(path2);
SampleUtilities.CheckDirectoryExists(destDir);

// Load source images
var source1 = new Bitmap(path1);
var source2 = new Bitmap(path2);

// Prepare for result image
var layer1 = new Bitmap(source1.Width, source1.Height); // new layer apparently includes alpha layer...
var layer2 = new Bitmap(source2.Width, source2.Height); // ... even when source does not.

using (var result = new Bitmap(source1.Width, source1.Height))
{
var blender = Graphics.FromImage(result);
blender.CompositingMode = CompositingMode.SourceOver; // NOT SourceCopy mode

// Sequential
SampleUtilities.TimedRun(() =>
SeqentialImageProcessing(source1, source2, layer1, layer2, blender),
"       Sequential");

// restore layers to iniital condition; layer2 must be unrotated
layer1 = new Bitmap(source1.Width, source1.Height);
layer2 = new Bitmap(source2.Width, source2.Height);

// Parallel tasks
SampleUtilities.TimedRun(() =>
ParallelTaskImageProcessing(source1, source2, layer1, layer2, blender),
"   Parallel tasks");

// restore layers to initial condition; layer2 must be unrotated
layer1 = new Bitmap(source1.Width, source1.Height);
layer2 = new Bitmap(source2.Width, source2.Height);

// Parallel invoke
SampleUtilities.TimedRun(() =>
ParallelInvokeImageProcessing(source1, source2, layer1, layer2, blender),
"  Parallel invoke");

// Save blended image in file
result.Save(Path.Combine(destDir, "blended.jpg"));

// Show blended image on screen, pause until user closes window
Console.WriteLine("Close image window to exit program.");
using (var form = new Form())  // ensure disposal, prevent warning CA2000
{
using (var pb = new PictureBox())
{
pb.SizeMode = PictureBoxSizeMode.AutoSize; // fit to image - but form is initially smaller
pb.Image = result;
form.Controls.Add(pb);
form.ShowDialog();
}
}
} // using result
}
}
}

# data[].attributes.body
https://www.facebook.com/groups/447786423719702

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace prog2017_008_of_LMS_maxDegreeParallelism
{
class Program
{
static void Main(string[] args)
{
const int newline_num = 3;
Parallel.For(0, 20, i =>
{
Console.WriteLine("MaxDegreeofParallelism is not defined: i={0}, thread = {1}", i,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
});
for (int i = 0; i < newline_num; i++) Console.WriteLine();

Parallel.For(0, 20, new ParallelOptions{MaxDegreeOfParallelism = 2},i=>
{
Console.WriteLine("MaxDegreeOfParallelism=2 -->: i={0}, thread = {1}", i,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}
);
for (int i=0;i< newline_num; i++) Console.WriteLine();

ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 4;
Parallel.For(0, 20, options, i =>
{
Console.WriteLine("MaxDegreeOfParallelism=4 -->: i={0}, thread = {1}", i,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}
);
for (int i = 0; i < newline_num; i++) Console.WriteLine();

options.MaxDegreeOfParallelism = -1;
Parallel.For(0, 20, options, i =>
{
Console.WriteLine("MaxDegreeOfParallelism= -1 -->: i={0}, thread = {1}", i,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}
);
Console.ReadLine();
}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prog2017_018_Future_and_Exception
{
class Program
{        static int F1_power(int b, int exp)
{
try
{
int r = 1;
for (int i = 0; i < exp; i++)
{
r = r * b;
}
Console.WriteLine("F1_power({0},{1}) success, result = {2}", b, exp, r);
return r;
}
catch(AggregateException)
{
Console.WriteLine("Exception occurs in F1_power");
return -1;
}
}

static int F4_DIV(int dividend,int divisor)
{
try
{
int a = dividend / divisor;
return a;
}
catch (AggregateException)
{
Console.WriteLine("Exception occurs in F4_DIV");
return -1;
}
}

static int F2_squared(int x)
{
try
{
return x * x;
}
catch (AggregateException)
{
Console.WriteLine("Exception occures in F2_squared");
return -1;
}
}

static int F3_factorial(int x)
{
try
{
if (x == 1)
return 1;
else
return x * F3_factorial(x - 1);
}
catch (AggregateException)
{
Console.WriteLine("Exception occures in F3_factorial");
return -1;
}
}

static int F5_cubed(int x)
{
try
{
return x*x*x;
}
catch (AggregateException)
{
Console.WriteLine("Exception occurs in F5_cubed");
return -1;
}
}

static void Main(string[] args)
{
int a = 15;
int b = 5;
int c = 1;
Task<int> futureD = Task.Factory.StartNew<int>(() => F2_squared(F3_factorial(b)));
Task<int> futureB = Task.Factory.StartNew<int>(() => F1_power(a, F4_DIV(b, c)));
try
{
int f = F4_DIV(futureD.Result, futureB.Result);
Console.WriteLine("F4_DIV [F2_squared(F3_factorial({1}), F1_power({0}, {1})] = {2}", a, b, f);
}
catch (AggregateException)
{
Console.WriteLine("Exception occures in Main");
}

Console.ReadLine();

}
}
}

# data[].attributes.body
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;

namespace prog2017_018_of_LMS_thread_local_vs_manual_var
{
class Program
{
public static double MyInterlockedAdd(ref double location1, double value)
{
double newCurrentValue = location1; // non-volatile read, so may be stale
while (true)
{
double currentValue = newCurrentValue;
double newValue = currentValue + value;
newCurrentValue = Interlocked.CompareExchange(ref location1, newValue, currentValue);
if (newCurrentValue == currentValue)
return newValue;
}
}
static void Main(string[] args)
{
const int data_size = 5000000;
int[] data = new int[data_size];
int i;
double result_serial, result_parallel;
result_serial = 0.0;
result_parallel = 0.0;

//---initial values in the array
for (i = 0; i < data.Length; i++)
data[i] = i * i;

Stopwatch stopWatch = new Stopwatch();
long ex_time_serial, ex_time_parallel;

//---------------------------------------------------------------------------------
//---sequential
//---------------------------------------------------------------------------------
stopWatch.Start();
for (i = 0; i < data.Length; i++)
{
result_serial += ((Math.Sin((double)data[i]) - Math.Cos((double)data[i])) /
(Math.Sin((double)data[i]) + Math.Cos((double)data[i])));
}
stopWatch.Stop();
ex_time_serial = stopWatch.ElapsedMilliseconds;
Console.WriteLine("========================================\nSequential Program");
Console.WriteLine("the result = {0}", result_serial);
Console.WriteLine("Execution time = {0}", ex_time_serial);
Console.WriteLine("========================================");

//---------------------------------------------------------------------------------
//---parallel using Thread Local Variable
//---------------------------------------------------------------------------------
result_parallel = 0.0;
stopWatch.Reset();
stopWatch.Start();
Parallel.For<double>(0, data.Length, () => 0.0, (j, loop, partialResult) =>
{
partialResult += ((Math.Sin((double)data[j]) - Math.Cos((double)data[j])) /
(Math.Sin((double)data[j]) + Math.Cos((double)data[j])));
return partialResult;
},
(x) => MyInterlockedAdd(ref result_parallel, x)
);
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("====================================================================");
Console.WriteLine("Parallel Program using Thread Local Variable");
Console.WriteLine("the result = {0}", result_parallel);
Console.WriteLine("Execution time = {0}", ex_time_parallel);
Console.WriteLine("====================================================================");

//---------------------------------------------------------------------------------
//---parallel using Thread Local Variable 2
//---------------------------------------------------------------------------------
result_parallel = 0.0;
stopWatch.Reset();
stopWatch.Start();
Parallel.For(0, data.Length, j =>
{
double partialResult = 0.0;

});

Parallel.For<double>(0, data.Length, () => 0.0, (j, loop, partialResult) =>
{
partialResult += ((Math.Sin((double)data[j]) - Math.Cos((double)data[j])) /
(Math.Sin((double)data[j]) + Math.Cos((double)data[j])));
return partialResult;
},
(x) => MyInterlockedAdd(ref result_parallel, x)
);
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("====================================================================");
Console.WriteLine("Parallel Program using Thread Local Variable");
Console.WriteLine("the result = {0}", result_parallel);
Console.WriteLine("Execution time = {0}", ex_time_parallel);
Console.WriteLine("====================================================================");

//---------------------------------------------------------------------------------
//---parallel using Parallel Aggregation
//---------------------------------------------------------------------------------
result_parallel = 0.0;
object lockObject = new object();
stopWatch.Reset();
stopWatch.Start();
Parallel.ForEach(
// The values to be aggregated
data,

// The local initial partial result
() => 0.0d,

// The loop body
(x, loopState, partialResult) =>
{
double r_sin, r_cos;
r_sin = Math.Sin((double)x);
r_cos = Math.Cos((double)x);
//local_result += (r_sin - r_cos) / (r_cos + r_sin);

return (r_sin - r_cos) / (r_cos + r_sin) + partialResult;
},

// The final step of each local context
(localPartialSum) =>
{
// Enforce serial access to single, shared result
lock (lockObject)
{
result_parallel += localPartialSum;
}
});
stopWatch.Stop();
ex_time_parallel = stopWatch.ElapsedMilliseconds;
Console.WriteLine("====================================================================");
Console.WriteLine("Parallel Program using Parallel-aggregation pattern");
Console.WriteLine("the result = {0}", result_parallel);
Console.WriteLine("Execution time = {0}", ex_time_parallel);
Console.WriteLine("====================================================================");

Console.ReadLine();
}
}
}