C # Multi-threading, cross-threading and thread-safe examples

Source: Internet
Author: User
Tags sleep static class

C # Multi-threading, thread-and-thread-safe examples (three different methods)

The code is as follows Copy Code

Using System.Threading;
public static Class Extensions
{
Control extension methods (for cross threading operations) because it prevents a deadlock or inconsistent state of resource contention for thread security. NET is not allowed to access a form control across threads.
public static void Safecall (this control CTRL, Action callback)
{
if (ctrl. invokerequired)
{
Ctrl. Invoke (callback);
}
Else
{
Callback ();
}
}
}

public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
Checkforillegalcrossthreadcalls = false;//Method Two (disables exceptions, does not check security issues that are invoked across threads, you can drag the form freely, but it is not desirable under strict conditions, data may be inconsistent)

Method Three (recommended use)
Use the code you want to protect as a callback, and then any place that needs to protect some code can call
ThreadPool.QueueUserWorkItem (H =>
{
int i = 0;
while (true)
{
If there is no Safecall method, the thread operation is invalid: it is accessed from a thread that is not creating the control "TextBox1". "The error

Anonymous delegate
Textbox1.safecall (Delegate ()
//{
TextBox1.Text = (i++). ToString ();
//});
Lambda expression
Textbox1.safecall (() =>
{
TextBox1.Text = (i++). ToString ();
});
Thread.Sleep (100);
}
});
}

Lottery examples
public bool flag = TRUE;
public void Choujiang ()
{
Flag = true;
while (flag)
{
Random rnd = new Random ();
TextBox1.Text = rnd. Next (1, 100). ToString ();
Application.doevents ()//method One: This can also prevent the UI interface thread from blocking, not to be stuck. But when you drag an interface or other action, the program is paused
}
}
Begin
private void Button1_Click (object sender, EventArgs e)
{
Choujiang ()//Method one
New Action (Choujiang). BeginInvoke (null, NULL);//Method Two
}
Time out
private void Button2_Click (object sender, EventArgs e)
{
Flag = false;
}
}


Asynchronous thread pool

The code is as follows Copy Code

Delegate Double Weituo (double D);
static Weituo w = new Weituo (perimeter);
<summary>
Calculate perimeter
</summary>
<param name= "D" ></param>
public static double perimeter (double D)
{
return d * MATH.PI;
}
<summary>
Method of callback after asynchronous completion
</summary>
<param name= "Result" ></param>
public static void method (IAsyncResult result)
{
Console.Write ("hi~");
Console.WriteLine (W.endinvoke (Result));
}

static void Main (string[] args)
{
Start asynchronous execution
W.begininvoke (New AsyncCallback (method), NULL);
W.begininvoke (New AsyncCallback (method), NULL);
Console.read ();
}

_________________________________
<summary>
Static methods do not need to be instantiated
</summary>
<param name= "D" ></param>
public static void Perimeter (object D)
{
Console.WriteLine (Math.PI * (double) d);
Thread.Sleep (1000);
}
static void Main (string[] args)
{
int i = 1;
WaitCallback WCB = new WaitCallback (perimeter);
while (I < 15)
{
Queues a task for execution, and your callback method executes when a thread pool threads are available
ThreadPool.QueueUserWorkItem (WCB, (double) i);
++i;
}
Console.read ();
}

Summarize

Advantages:
• Use a thread to put tasks in a long-running program into the background to handle
• User interface can be more attractive, such as users click a button to trigger the processing of certain events, you can pop a progress bar to show the progress of processing
• Programs may run faster
• Threads are more useful in waiting tasks such as user input, file read and write, and network transceiver data. In this case we can release some valuable resources such as memory footprint and so on.

Disadvantages:
• If there are a large number of threads, it can affect performance because the operating system needs to switch between them;
• More threads require more memory space
• Threads can bring more bugs to the program, so be careful with
• Thread abort needs to consider its impact on program operation
• Typically block model data is shared among multiple threads, requiring a suitable lock system to replace data sharing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.