"Go" multithreading Summary in C # for absolute novice C #

Source: Internet
Author: User

There are about 4 ways to do this:
Dispatcher, asynchronous delegate, manual multithreading, BackgroundWorker, There is also a dispatchertimer, is a timer.

Where dispatcher is the same as DispatcherTimer, it is used to simulate multi-threading by arranging task priorities in the main thread, so the substance is single-threaded

, so it is not advisable to use them for heavy load operations. When calling asynchronously, use Dispatcher.invoke (AddItem, image);


BackgroundWorker will go to the thread pool to grab a thread as a worker, switch back to the UI thread after the work is done, call the task you defined to complete the process.

Sorrento Each time a value is calculated, the worker is used. ReportProgress (PercentComplete) notifies the callback function and can update the UI in the callback function. Special

Not suitable for scenarios where you need to update a completed percentage.

These can all be combined with data binding.

① asynchronous delegate or manual multithreading
Asynchronous Delegate : Supports callback at end of thread (the first parameter of the BeginInvoke method), but does not support disconnected threads outside, and is used to update the UI.

Manual Threading : Supports external thread break (Thread.Abort method), but it is not easy to get the return value of the function. In addition, the UI cannot be updated. Because the Windows

The form uses a single-threaded apartment (STA) model, as is the case with WPF forms, the STA model means that Windows can be created on any thread, but once the window is created

The thread cannot be switched, and all function calls to it must occur on its creation thread. In particular, be careful in registering event callback functions.

usage of delegate:

[C-sharp] View plaincopy

    1. public class Mydelegatetest
    2. {
    3. Step 1, declaring the delegate object
    4. Public delegate bool MyDelegate (string name);
    5. This is the method we want to pass, which has the same parameters and return value types as the MyDelegate
    6. public static bool Mydelegatefunc (string name)
    7. {
    8. Console.WriteLine ("Hello, {0}", name);
    9. return ture;
    10. }
    11. public static Voidmain ()
    12. {
    13. Step 2, create the delegate object
    14. MyDelegate MD = new MyDelegate (MYDELEGATETEST.MYDELEGATEFUNC);
    15. Step 3, call delegate
    16. Console.WriteLine ("Result is {0}", MD ("sam1111"));
    17. }
    18. }

This method of invocation, like invoke with the delegate object, is a synchronous call that blocks the current thread. Asynchronous calls require the use of BeginInvoke:

[C-sharp] View plaincopy

  1. Class Program
  2. {
  3. private static int NewTask (int ms)
  4. {
  5. Console.WriteLine ("Task Start");
  6. Thread.Sleep (MS);
  7. Random random = new random ();
  8. int n = random. Next (10000);
  9. Console.WriteLine ("Mission Accomplished");
  10. return n;
  11. }
  12. Private delegate int newtaskdelegate (int ms);
  13. static void Main (string[] args)
  14. {
  15. Newtaskdelegate task = NewTask;
  16. IAsyncResult AsyncResult = task. BeginInvoke (+, NULL, NULL); EndInvoke method will be blocked 2
  17. Seconds
  18. Do Something Else
  19. int result = task. EndInvoke (AsyncResult);
  20. Console.WriteLine (result);
  21. }
  22. }

The BeginInvoke here is an asynchronous call that returns immediately after the run, without causing the current thread to block. But in this routine, because the NewTask

In Sleep 2 seconds, if the do Something else time does not have 2 seconds, EndInvoke will still cause the current thread to block because it waits for

NewTask execution is complete.

Can you not call EndInvoke and let it end by itself? Not very good. Because a BeginInvoke and EndInvoke must be called in pairs. Even if you do not need to return

return value, but EndInvoke still must be called, otherwise it may cause a memory leak because it is leveraging the thread pool resource. Secondly, we often call EndInvoke

To get the return value of the function.

If the BeginInvoke is used for polling, EndInvoke cannot be returned, then a variable can be used to control it:
In my application scenario, a wrapper class is defined:

[C-sharp] View plaincopy

  1. Class Isnetworkavailabledelegate
  2. {
  3. Private Isnetworkavailablewrapper _available;
  4. Private delegate void MyDelegate ();
  5. Private MyDelegate _dele;
  6. Private IAsyncResult _result;
  7. private bool _running = true;
  8. private void Tryconnect ()
  9. {
  10. while (this._running)
  11. {
  12. Try
  13. {
  14. Ping _ping = new Ping ();
  15. if (_ping. Send ("www.baidu.com"). Status = = ipstatus.success)
  16. This._available. Isnetworkavailable = true;
  17. Else
  18. This._available. Isnetworkavailable = false;
  19. }
  20. Catch
  21. {
  22. This._available. Isnetworkavailable = false;
  23. }
  24. Thread.Sleep (500);
  25. }
  26. }
  27. Public Isnetworkavailabledelegate (Isnetworkavailablewrapper available)
  28. {
  29. This._available = available;
  30. This._dele = new MyDelegate (this. Tryconnect);
  31. This._result = This._dele. BeginInvoke (null, NULL);
  32. }
  33. public void EndInvoke ()
  34. {
  35. This._running = false;
  36. This._dele. EndInvoke (This._result);
  37. }
  38. }

To be completely asynchronous with the current thread, you can use the second parameter of BeginInvoke to set a callback function after the function executes:

[C-sharp] View plaincopy

    1. Private delegate int mydelegate (int a);
    2. private int method (int a)
    3. {
    4. Thread.Sleep (10000);
    5. Console.WriteLine (a);
    6. return 100;
    7. }
    8. private void methodcompleted (IAsyncResult asyncResult)
    9. {
    10. if (AsyncResult = = null) return;
    11. TextBox1.Text = (asyncresult.asyncstate as MyDelegate). EndInvoke (AsyncResult). ToString ();
    12. }
    13. private void Button1_Click (object sender, EventArgs e)
    14. {
    15. MyDelegate my = method;
    16. IAsyncResult AsyncResult = My. BeginInvoke (methodcompleted, my);
    17. }

This allows the current thread to feel no more waiting at all.

Sometimes, however, the current thread wants to take advantage of the time the function executes, and then do something else after the function is done, using the WaitOne method: Reverse telecommuting.

[C-sharp] View plaincopy

  1. Class Program
  2. {
  3. public delegate int Binaryopdelegate (int x, int y);
  4. static void Main (string[] args)
  5. {
  6. Console.WriteLine ("* * * * * Async Delegate Invocation * * * * * *);
  7. Print out the ID of the executing thread.
  8. Console.WriteLine ("Main () invoked on thread {0}.",
  9. THREAD.CURRENTTHREAD.MANAGEDTHREADID);
  10. Invoke Add () on a secondary thread.
  11. Binaryopdelegate B = new Binaryopdelegate (ADD);
  12. IAsyncResult Iftar = B.begininvoke (ten, ten, NULL, NULL);
  13. This message would keep printing until
  14. The Add () method is finished.
  15. Wait for asynchronous delegate execution to complete with WaitOne
  16. while (!iftar.asyncwaithandle.waitone (), True)
  17. {
  18. Console.WriteLine ("Doing more work in Main ()!");
  19. }
  20. Obtain the result of the ADD ()
  21. Method is ready.
  22. int answer = B.endinvoke (Iftar);
  23. Console.WriteLine ("Ten + Ten is {0}.", answer);
  24. Console.ReadLine ();
  25. }
  26. #region Very Slow addition ...
  27. static int Add (int x, int y)
  28. {
  29. Print out the ID of the executing thread.
  30. Console.WriteLine ("Add () invoked on thread {0}.",
  31. THREAD.CURRENTTHREAD.MANAGEDTHREADID);
  32. Simulate an act that takes a long time
  33. Pause to simulate a lengthy operation.
  34. Thread.Sleep (5000);
  35. return x + y;
  36. }
  37. #endregion
  38. }

(PS: Using lambda syntax can also write very good sentences:)

[C-sharp] View plaincopy

    1. action<object> action= (obj) =>method (obj);
    2. Action. BeginInvoke (obj,ar=>action. EndInvoke (AR), null);

In fact, it can be more direct:

[C-sharp] View plaincopy

    1. New Action<object> ((obj) = method (obj)). BeginInvoke (ar=>action. EndInvoke (AR), null);

The main function of the Invoke method is to help you invoke the method specified by the delegate on the UI thread. The Invoke method first checks the thread that made the call (that is, the current thread

is not a UI thread, if it is, directly executes the method that the delegate points to, if not, it switches to the UI thread, and then executes the method that the delegate points to.

Calls to the manual thread:
The typical notation is:

[C-sharp] View plaincopy

    1. public class Procclass
    2. {
    3. private string procparameter = "";
    4. private string result = "";
    5. Public Procclass (string parameter)
    6. {
    7. Procparameter = parameter;
    8. }
    9. public void ThreadProc ()
    10. {
    11. }
    12. }
    13. Procclass ThreadProc = new Procclass ("Use thread class");
    14. Thread thread = new Thread (new ThreadStart (Threadproc.threadproc));
    15. Thread. IsBackground = true;
    16. Thread. Start ();

Because a function called by thread can only be parameterless and has no return value, it is usually wrapped in a class.

If a thread needs to be interruptible, it also has to deal with the UI:

[C-sharp] View plaincopy

  1. public class Procclass
  2. {
  3. private string procparameter = "";
  4. Private form1.outdelegate Delg = null;
  5. Public Procclass (string parameter, Form1.outdelegate Delg)
  6. {
  7. Procparameter = parameter;
  8. This.delg = Delg;
  9. }
  10. public void ThreadProc ()
  11. {
  12. Delg. BeginInvoke ("Use Procclass.threadproc ()", NULL, NULL);
  13. }
  14. }
  15. Procclass ThreadProc = new Procclass ("Use Thread class", New Outdelegate (Outtext));
  16. Thread thread = new Thread (new ThreadStart (Threadproc.threadproc));
  17. Thread. IsBackground = true;
  18. Thread. Start ();

"Go" multithreading Summary in C # for absolute novice C #

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.