Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The use of C # multithreaded Task

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "the use of C# multithreaded Task". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the use of C# multithreaded Task".

Background

When our program is performing data processing for a long time, if only the main process is used, the waiting time will be long. If we use multi-thread operation in this time, we can not only reduce the time-consuming, but also simply synchronize the UI interface in the execution process, so that people can see that there will be no false death.

Request

We want to reach 30 W of data, divided into 6 tasks, each task processes 5 W of data, and then 3 parallel tasks. After each task traverses, a TXT file is generated.

Design ideas

We add multiple user controls through multiple tasks, and then set the bool type in the TAG of the control to determine whether the task has been executed, and then first find the unexecuted task during the thread operation, then update the TAG flag and process the task, and then write the data to the txt file under the current directory after processing the current task data, until all the tasks are completed and finish the thread.

Knowledge point

Design of user Control

Dynamically create a control

Operation of thread Task

Coding

Open VS, I use 2017, and create a new project named TaskDemo

In Form, we add three controls, namely FlowLayoutPanel, TextBox and a Button

The FlowLayoutPanel on the left is later we build a user control to display the task list, which can be arranged adaptively.

Next, we choose to add a new user control named TaskCtrl with the right mouse button in the solution.

After it is built, we will add a few Label and a ProgressBar to it.

Define three values in userctrl

/ / Task number

Public int Taskno

/ / number of records started

Public int Startrecord

/ / number of closing records

Public int Endrecord

Then change the constructor again

Public TaskCtrl (int taskno, int startrecord, int endrecord)

{

Taskno = taskno

Startrecord = startrecord

Endrecord = endrecord

InitializeComponent ()

LblTaskNo.Text = "Task number:" + Taskno

LblRecord.Text = "task records:" + (Endrecord-Startrecord)

Prgb.Minimum = Startrecord

Prgb.Maximum = Endrecord

Prgb.Value = Startrecord

}

Let's add another method to update the display of the current task

/ / /

/ / display progress bar and information

/ / /

/ / /

Public void ShowProgressbar (int row)

{

Prgb.Value = row

LblStatus.Text = row + "/" + Endrecord

}

In this way, we have completed the user control. Let's start writing the button event of the main interface.

First, we define several values, such as total data, the value of each task, and the number of parallel tasks at the same time.

Then we define a delegate that can be used to synchronize the current state of the UI display during thread execution

And then we started to write button events.

First write a method to initialize the user control

/ / /

/ / initialize flowlayoutpanel to get user control

/ / /

Private void InitFlowLayoutPanel ()

{

Flpnl.Controls.Clear ()

/ / count the number of tasks

/ / the total is divided by the maximum number of each task. If there is a remainder, the number of tasks + 1, if there is no remainder, the number of tasks.

Int taskqty = totalrecord% taskrecord > 0? Totalrecord / taskrecord + 1: taskrecord / taskrecord

/ / Loop to automatically create user controls

For (int I = 0; I

< taskqty; i++) { //计算当前任务的开始记录和结束记录 int startrecord = i == 0 ? 1 : i * taskrecord + 1; int endrecord = i == 0 ? taskrecord : (i + 1) * taskrecord; TaskCtrl userctrl = new TaskCtrl(i, startrecord, endrecord); userctrl.Name = "Task" + i; //Tag标志用于记录当前任务是否已经完成 userctrl.Tag = false; flpnl.Controls.Add(userctrl); } } 业务处理的核心代码 /// /// 线程操作 /// private void TaskModify() { Task parent = new Task(() =>

{

Var cts = new CancellationTokenSource ()

Var tf = new TaskFactory (cts.Token, TaskCreationOptions.AttachedToParent

TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default)

/ / define the tasks performed by the array

Task [] childTasks = new Task [tasknum-1]

/ / assignment

For (int task = 0; task)

< tasknum; task++) { childTasks [task] = tf.StartNew(() =>

{

Bool res = true

While (res)

{

Thread.Sleep (2000)

/ / get the return value after each execution to query whether there are any unfinished tasks.

/ / if execution continues, exit the thread if not

Res = DoTask ()

}

}, cts.Token) .ContinueWith (t = >

{

If (t.IsCompleted)

{

This.BeginInvoke (TextShow, "all current thread tasks have been executed!")

}

Else if (t.IsCanceled)

{

This.BeginInvoke (TextShow, "current thread cancels task!")

}

Else if (t.IsFaulted)

{

This.BeginInvoke (TextShow, "current thread exception!")

}

}, cts.Token)

Thread.Sleep (200)

}

});

Parent.Start ()

}

Code related to data processing

/ / /

/ / get the user control to determine whether the task has been completed

/ / /

/ / /

Private TaskCtrl GetUserCtrl ()

{

TaskCtrl ctrl = null

Foreach (Control c in flpnl.Controls)

{

Ctrl = c as TaskCtrl

/ / determine whether the user control has completed the task

If (ctrl! = null & &! (bool) ctrl.Tag)

{

Return ctrl

}

}

Return null

}

Private bool DoTask ()

{

Bool res = false

String str = string.Empty

/ / get the user control, and start the task if it is not empty

TaskCtrl taskCtrl = GetUserCtrl ()

If (taskCtrl! = null)

{

/ / Update the user control flag after acquisition

Res = true

TaskCtrl.Tag = res

/ / define the number of rows displayed last time

Int lastshow = 0

For (int row = taskCtrl.Startrecord; row

< taskCtrl.Endrecord; row++) { //拼接循环的字符串 str = str + "" + row + ""; //防止每条都更新UI造成阻塞,设置每1000条更新一次UI if (row - lastshow >

1000 | | row = = taskCtrl.Endrecord)

{

This.BeginInvoke (TaskProcessbar, taskCtrl, row)

Lastshow = row

}

}

This.BeginInvoke (TaskProcessbar, taskCtrl, taskCtrl.Endrecord)

/ / Save the stitched string after the loop to the txt file, and the file name is the user control name.

String filePath = Directory.GetCurrentDirectory () + "\\ file" + taskCtrl.Name + ".txt"

System.IO.File.WriteAllText (filePath, str, Encoding.UTF8)

}

Return res

}

Next, let's run it to see the effect.

Generate the corresponding txt file in the program directory after the task is executed

Thank you for your reading, the above is the content of "the use of C# multithreaded Task". After the study of this article, I believe you have a deeper understanding of the use of C# multithreaded Task, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report