[C #] The synchronization method is asynchronous rewriting

[C #] The synchronization method is asynchronous rewriting


Foreword

When we come across a program that takes a long time,

We usually call it via an asynchronous manner (such as reading BeginRead data stream, EndRead),

If that method could have been synchronized, there is no way we can rewrite it do?

This theme is to introduce how the synchronization (sync) program rewrite asynchronous (async) program.

Practical exercises

In .Net Framework, the asynchronous model (APM) can be roughly divided into two categories,

IAsyncResult based asynchronous model, and Event Based asynchronous model,

We first build a very simple addition function, and add it to simulate Thread.Sleep spend a lot of time,


public class Calculator
{
        public int Calculate(int a, int b)
        {
            // 模拟花费大量时间运算
            System.Threading.Thread.Sleep(10 * 1000);

            return a + b;
        }
}

通常在程序中执行此函数时看起来会像这样,程序会卡在这边非常久

Calculator calculator = new Calculator();
// 程序会停在这边很长的时间
int result = calculator.Calculate(1, 2);

Next, how to rewrite this function is called asynchronous mode available

1. rewrite IAsyncResult based asynchronous model

First, we must first establish a same function Input and Output of delegate,

Because after version 3.5 has built-in Func, so in today's paradigm to directly use Func as a delegate,


//In 2.0, sample, not work
//private delegate int CalculateDelegate(int a,int b);
//CalculateDelegate m_calculateDelegate = new CalculateDelegate(Calculate);
private Func
  
  
   
    m_calculateDelegate;
  
  

Then we can follow BeginRead and read the same data stream EndRead were written BeginCalculate and EndCalculate method,


public IAsyncResult BeginCalculate(int a, int b)
{
    this.m_calculateDelegate = this.Calculate;

    return this.m_calculateDelegate.BeginInvoke(a, b, null, null);
}

public int EndCalculate(IAsyncResult asyncResult)
{
    return this.m_calculateDelegate.EndInvoke(asyncResult);
}

In this way, we call BeginCalculate and EndCalculate on asynchronous methods can be used in the program,

And before the program can be calculated, to continue to do other things,


Calculator calculator = new Calculator();
IAsyncResult asyncResult = calculator.BeginCalculate(1, 2);

// Do something else

int result = calculator.EndCalculate(asyncResult);

 2. rewrite asynchronous model of Event Based 


Event Based的异步模型,在执行完毕之后会将主控权交还给程序,

不会阻塞目前的Thread,一直到执行完毕之后,才会触发注册的事件。

首先我们建立一个当执行完毕时会触发的事件,并且会传入具有计算结果的EventArgs

public event EventHandler
  
  
   
    CalculateFinished;

public class CalculateFinishedEventArgs : EventArgs
{
    public int Result { get; private set; }

    public CalculateFinishedEventArgs(int result)
    {
        this.Result = result;
    }
}
  
  

We have established a method CalculateAsync again for calling program, and does not block the execution after Thread,

And it will be finished after the trigger event CalculateFinished,


public void CalculateAsync(int a, int b)
{
      this.m_calculateDelegate = Calculate;

      AsyncCallback callback = new AsyncCallback(OnCalculateFinished);
      this.m_calculateDelegate.BeginInvoke(a, b, callback, m_calculateDelegate);
}

private void OnCalculateFinished(IAsyncResult asyncResult)
{
      Func calculateDelegate = (Func)asyncResult.AsyncState;

      int result = calculateDelegate.EndInvoke(asyncResult);

      EventHandler temp = CalculateFinished;
      if (temp != null)
      {
           temp(this, new CalculateFinishedEventArgs(result));
      }
}

,>,>

Program execution can be rewritten as


Calculator calculator = new Calculator();         

calculator.CalculateFinished += (o, args) => MessageBox.Show(string.Format("Result is {0}", args.Result));
calculator.CalculateAsync(1, 2);

// Do other works...

Epilogue

For efficient use of system resources, parallel jobs, and provide users with a good user experience,

When using the asynchronous method call writing program is indispensable,

But at the same time writing asynchronous programs, but often result in a more piecemeal program,

And less likely to read and maintain troubled, in the next article,

Will introduce how to use Iterator to improve the situation,

Of course, the previously described method of asynchronous call may also be utilized in and out of the processing window,

Thread or through BackgroundWorker way to handle,

We also welcome with a lot of discussion and advice Hello ^ _ ^

Reference data:

1. http://msdn.microsoft.com/zh-tw/library/2e08f6yc(v=VS.100).aspx asynchronously call synchronous methods

2. http://msdn.microsoft.com/zh-tw/magazine/cc163467.aspx practice writing program Asynchronous CLR model

Original: Large column  [C #] The synchronization method to rewrite asynchronous methods


Guess you like

Origin www.cnblogs.com/chinatrump/p/11516588.html