In the group today , Someone asked

There are several void Methods to return values , But I want these methods to have execution order , What to do with ,ABCD Four ways , Execute sequentially , But these methods have no return value

The question is very simple , If the method is synchronous , Just write directly in four consecutive ways , such as :

    static void Main()
{
A();
B();
C();
D();
}

But if the method contains time-consuming operations , Then there is a problem with writing four in this way , The execution sequence is wrong , We need to use callback Function to operate , But in line with the idea of not moving the original method , We use Task Of OnCompleted event (.net framework Can be used in BeginInvoke(callback,null)) To deal with

  1. If the method has a return value , Then use Func, perhaps Func<>
  2. If the method does not return a value , Then use Action, perhaps Action<>

1. No return value in .net core Use in Task Of OnCompleted event

Because it is a method without return value , We use

for example

     static void Main()
{
Action action1 = () => {
Thread.Sleep(1000);
Console.WriteLine("action1");
}; Action action2 = () => {
Thread.Sleep(2000);
Console.WriteLine("action2");
}; Action action3 = () => {
Thread.Sleep(3000);
Console.WriteLine("action3");
}; Action action4 = () => {
Thread.Sleep(3000);
Console.WriteLine("action4");
};
Stack st = new Stack();
st.Push(action2);
st.Push(action3);
st.Push(action4); void MyAsynCallback()
{
if (st.Count > 0)
{
var action = (Action)st.Pop();
Task.Run(action).GetAwaiter().OnCompleted(() =>
{
MyAsynCallback();
});
}
}
Task.Run(action1).GetAwaiter().OnCompleted(() =>
{
MyAsynCallback();
});
Console.ReadLine();
//Stack Of Pop First in, then out , Output order action1 action4 action3 action2
}

We can Stack Change it to something else , such as List、Queue etc. , Decide whether you need to pop it up manually action that will do

2. No return value in .net framework Use in BeginInvoke

     static void Main()
{
Action action1 = () => {
Thread.Sleep(1000);
Console.WriteLine("action1");
}; Action action2 = () => {
Thread.Sleep(2000);
Console.WriteLine("action2");
}; Action action3 = () => {
Thread.Sleep(3000);
Console.WriteLine("action3");
}; Action action4 = () => {
Thread.Sleep(3000);
Console.WriteLine("action4");
};
Stack st = new Stack();
st.Push(action2);
st.Push(action3);
st.Push(action4); void MyAsynCallback(IAsyncResult async)
{
if (st.Count > 0)
{
var action = (Action)st.Pop();
action.BeginInvoke(new AsyncCallback(MyAsynCallback),null);
}
}
action1.BeginInvoke(new AsyncCallback(MyAsynCallback), null);
Console.ReadLine();
//Stack Of Pop First in, then out , Output order action1 action4 action3 action2
}

3. There is a return value in .net core Use in Task Of OnCompleted event

Because it is a method without return value , We use

for example

     static void Main()
{
Func<int> func1 = () => {
Thread.Sleep(1000);
Console.WriteLine("func1");
return 1;
}; Func<int> func2 = () => {
Thread.Sleep(2000);
Console.WriteLine("func2");
return 1;
}; Func<int> func3 = () => {
Thread.Sleep(3000);
Console.WriteLine("func3");
return 0;
}; Func<int> func4 = () => {
Thread.Sleep(3000);
Console.WriteLine("func4");
return 1;
};
Stack st = new Stack();
st.Push(func2);
st.Push(func3);
st.Push(func4); void MyAsynCallback(int result)
{
if (st.Count > 0 && result > 0)
{
var action = (Func<int>)st.Pop();
var task1 = Task.Run(action);
task1.GetAwaiter().OnCompleted(() =>
{
MyAsynCallback(task1.Result);
});
}
}
var task = Task.Run(func1); task.GetAwaiter().OnCompleted(() =>
{
MyAsynCallback(task.Result);
});
Console.ReadLine();
//Stack Of Pop First in, then out , Output order func1 func4 func3 func2
}

4. There is a return value in .net framework Use in BeginInvoke

     delegate int dele_func(int a);
static void Main()
{
Func<int> func1 = () => {
Thread.Sleep(1000);
Console.WriteLine("func1");
return 1;
}; Func<int> func2 = () => {
Thread.Sleep(2000);
Console.WriteLine("func2");
return 1;
}; Func<int> func3 = () => {
Thread.Sleep(3000);
Console.WriteLine("func3");
return 1;
}; Func<int> func4 = () => {
Thread.Sleep(3000);
Console.WriteLine("func4");
return 1;
};
Stack st = new Stack();
st.Push(func2);
st.Push(func3);
st.Push(func4); void MyAsynCallback(IAsyncResult async)
{
dele_func dele_Func2 = (dele_func)async.AsyncState;
int result = dele_Func2.EndInvoke(async);
if (st.Count > 0 && result > 0)
{
var action = (Func<int>)st.Pop();
dele_func dele_Func1 = new dele_func((int a) => { return action.Invoke(); });
IAsyncResult asyncResult1 = dele_Func1.BeginInvoke(0, new AsyncCallback(MyAsynCallback), dele_Func1);
}
}
dele_func dele_Func = new dele_func((int a) => { return func1.Invoke(); });
IAsyncResult asyncResult = dele_Func.BeginInvoke(0, new AsyncCallback(MyAsynCallback), dele_Func);
Console.ReadLine();
//Stack Of Pop First in, then out , Output order func1 func4 func3 func2
}

When there is a return value , According to result The judgment of the , To determine whether to proceed

If there is a problem , Welcome to correct

ABCD Four sequential execution methods , More related articles on expansionary extension

  1. c# Threads execute sequentially

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

  2. Node.js The pits of —— How to make asynchronous concurrent methods execute synchronously and sequentially (for loop + Asynchronous operations )

    1  Preface nodejs The callback , Sometimes people really love and hate , When you need to use for The loop stores the data in the database in turn , But if you use normal for loop , It is always the record of the last value , It doesn't meet the requirements at all . There are several solutions , Such as closures ( ...

  3. Three threads T1,T2,T3. There are three ways to ensure sequential execution

    I often see interview questions : There are three threads T1,T2,T3, What's the way to make sure they're executed in order . I did a handwriting test today , Here's what I'm thinking of 3 Type of implementation explain : Here I use it in threads sleep Method , The aim is to make it easier to find problems . Before ...

  4. ajax Asynchronous cause js Method sequence cannot be executed

    js The order of the two method calls , Sometimes it's like this f1(); f2(); It was originally executed first f1 Of , But if f1 Carry out inside ajax asynchronous     async:true, Then it may be executed first f2, If you want to execute in sequence , Then set asynchrony ...

  5. c# There are four methods of data execution (ExecuteNonQuery)----- Reprint

    c# There are four methods of data execution (ExecuteNonQuery)   1. Use ExecuteReader() Operating the database 2. Use ExecuteNonQuery() Operating the database 3. Use ExecuteScalar( ...

  6. Use timer judgment to ensure that a tag has a value before executing the method , control js Code execution sequence

    Use timer judgment to ensure that a tag has a value before executing the method : var wait = setInterval(function(){ var diqu = $("#diqu").val(); // Make sure ...

  7. More elegant way : JavaScript Execute asynchronous functions sequentially in

    Fire is asynchronous 1995 year , The most popular browser of the time -- Start running in Netscape JavaScript ( Originally known as LiveScript). 1996 year , Microsoft released JScript compatible JavaScript. With Netscape . tiny ...

  8. {Django Foundation nine middleware } One Foreplay Two Middleware introduction 3、 ... and Custom middleware Four The execution process of middleware 5、 ... and Middleware version login authentication

    Django Foundation nine middleware Contents of this section One Foreplay Two Middleware introduction 3、 ... and Custom middleware Four The execution process of middleware 5、 ... and Middleware version login authentication 6、 ... and xxx 7、 ... and xxx 8、 ... and xxx One Foreplay We have learned in the previous course ...

  9. js Parallel loading and sequential execution

    Review this paragraph again , It's really a big deal to find the compatibility of various browsers , It's troublesome to deal with . Now to summarize, load multiple in parallel js Methods : 1, For dynamic createElement('script') The way , For all browsers ...

  10. 【 original 】cs+html+js+css Pattern ( 7、 ... and ): Sequential execution and concurrent execution ,IIS7 And above versions of the throwing error problem solving

          In the process of development , For this mode , We inherited IRequiresSessionState, For our same IIS The execution of is sequential, that is, a ajax After the request is processed , To execute the next ajax, ...

Random recommendation

  1. iOS hide the status bar

    1. Hide the status bar throughout the project stay Targets->General-> Check Hide status bar . Hide the status bar throughout the project 2. A single interface hides the status bar , For example, log in to the registration page 1. First, in the info.p ...

  2. KMP Algorithm learning

    kmp The task of the algorithm is : Given two strings O and f, The lengths are n and m, Judge f Whether in O It appears that , If it appears, return to where it appears . The normal way is to traverse a Every position of , Then start from that position and b Match , But the complexity of this approach is O(n ...

  3. linux Next ntfs Mobile hard disk mount

    fdisk -l Disk /dev/sdb: 500.0 GB, 500074283008 bytes255 heads, 63 sectors/track, 60797 cylindersUnit ...

  4. Word2010 The undo button fails ,Ctrl+Z Failure resolution

    1. Open registry editor . Press Win+R, Type... In the run box regedit, And then click “ determine ”. 2. In the registry editor , Expand to the following registry subkeys : HKEY_CURRENT_USER\Software\Microso ...

  5. stay Dynamics CRM 2015 Pass through 3CX plug-in unit ( as well as 3CX windows phone) Dial out the phone

    background stay On-premises The deployment of Dynamics CRM Realize the function of dialing customer's phone through web page The main points of 3CX Provide out of the box Dynamics CRM Solution, Only need Microsoft Dy ...

  6. UML: Activity diagrams

    Excerpt from http://www.umlonline.org/school/thread-36-1-1.html Activity diagrams and flow charts are very similar , Let's take a look at an example of a flow chart : Activity diagram is a kind of diagram used to describe process , It is different from the flow chart ...

  7. VC++ 0xC0000005: Access violation.

    public: COptionDlg(CWnd* pParent = NULL); // Standard constructors virtual ~COptionDlg(); TCONFIG m_tCfg; // Dialog data ...

  8. Use kdbg or nemiver debugging ROS

    Kdbg Kdbg yes KDE One in the environment gdb The front end of the GUI, It's friendly to use , It's also very fast , Please refer to : http://www.kdbg.org/ stay UBUNTU You can use it directly APT install : sudo ...

  9. MySQL How to use index optimization ORDER BY Sort statement 【 Reprint 】

    Reprinted from :http://blog.csdn.net/ryb7899/article/details/5580624  . Thanks to the authors . MySQL Indexes are usually used to improve WHERE The data line of the condition matches or executes ...

  10. Oracle left Query case

    )) summoney from( select t2.ano,d.dmoney from ( select t1.*,c.cno from( select a.ano,b.bno from t_a ...