C Multithreaded Parameter and Task Usage Example
- 2021-10-16 02:29:38
- OfStack
This paper illustrates the usage of C # multithreading parameters and tasks. Share it for your reference, as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" This is the main thread ");
DateTime dtStart = DateTime.Now;
for (int i = 0; i < 100; i++)
{
Student s = new Student();
s.name = " Zhang 3" + i;
s.sex = " Male ";
s.age = 28;
Thread t = new Thread(ThreadWithParas);
t.Start(s); // To pass data to threads, you need a class or structure that stores data
}
DateTime dtEnd = DateTime.Now;
TimeSpan span = (TimeSpan)(dtEnd - dtStart);
Console.ReadLine();
Console.WriteLine(" Running time " + span.Milliseconds);
Console.ReadLine();
}
static void ThreadWithParas(object o)
{
Student s = o as Student;
Console.WriteLine(" This is a split thread " + Thread.CurrentThread.ManagedThreadId + " " + s.name + "---" + s.sex + "---" + s.age);
}
}
public class Student
{
public string name;
public string sex;
public int age;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleSample
{
class Program
{
static void Main(string[] args)
{
// Task hierarchy
Task parent = new Task(ParentTask);
parent.Start();
Thread.Sleep(2000);
Console.WriteLine(parent.Status);
Thread.Sleep(4000);
Console.WriteLine(parent.Status);
Console.ReadLine();
}
// Parent task
static void ParentTask()
{
Console.WriteLine("task id {0}", Task.CurrentId);
Task child = new Task(ChildTask); // , TaskCreationOptions.DetachedFromParent);
child.Start();
Thread.Sleep(1000);
Console.WriteLine("parent started child");
// Thread.Sleep(3000);
}
// Subtask
static void ChildTask()
{
Console.WriteLine("child");
Thread.Sleep(5000);
Console.WriteLine("child finished");
}
}
}
For more readers interested in C # related content, please check out the topics on this site: "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"
I hope this article is helpful to everyone's C # programming.