How to write an async class with a minimal amount of re-code?

How to write an async class like WebClient?

Anyway, can I keep it short and don't need to repeat it for each method?

For example, I have:

Download(string a)
Download(string a, string b)

Do I need to rewrite the Async + Complete method for each of them?

Many thanks.

+3
source share
4 answers

Use MethodInvoker.BeginInvoke to invoke the new thead.

0
source

Update:

This example is for winforms, and I believe the OP is asking about asp.net. I will review my answer as soon as I have feedback from my comments.


. , .Net - BackgroundWorker. ++.

MSDN , , ( - ):

private BackgroundWorker bw;

private void foobar() {
  bw = new BackgroundWorker(); // should be called once, in ctor
  bw.DoWork += new DoWorkEventHandler(bw_DoWork);
  bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_Completed);

  int i = 0;
  bw.RunWorkerAsync(i);
}

private void bw_DoWork(object sender, DoWorkEventArgs e) {
  int i = (int)e.Argument;
  i++;
  e.Result = i;
}

private void bw_Completed(object sender, RunWorkerCompletedEventArgs e) {
  if (e.Error != null) {
    MessageBox.Show(e.Error.Message);
  } else {
    int i = (int)e.Result;
    MessageBox.Show(i.ToString());
  }
}

, , , , . , .

+3

, . http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx. Async Complete.

, , IAsyncResult, IAsyncResult ( , Framework, ). Async Complete, .

+1

, , , , WebClient?

, , .NET , . , , Stream, BeginRead EndRead. IAsyncResult , , . ( MSDN)

async , , WebClient, DownloadString/DownloadStringAsync DownloadStringCompleted. , , , , Begin/End.

, . , , . Download/DownloadAsync, DownloadCompleted, .

Here is a very simple implementation. Note that the only method that really does any work is a single synchronous boot method. It is also important to note that this is not the most efficient way to do this. If you want to take advantage of the async IO HttpWebRequest and the like, this example will quickly get complicated. There's also an overly complex Async Operation that I never liked a single bit.

class Downloader {

    public void Download(string url, string localPath) {
        if (localPath == null) {
            localPath = Environment.CurrentDirectory;
        }
        // implement blocking download code
    }

    public void Download(string url) {
        Download(url, null);
    }

    public void DownloadAsync(string url, string localPath) {

        ThreadPool.QueueUserWorkItem( state => {

            // call the sync version using your favorite
            // threading api (threadpool, tasks, delegate.begininvoke, etc)
            Download(url, localPath);

            // synchronizationcontext lets us raise the event back on
            // the UI thread without worrying about winforms vs wpf, etc
            SynchronizationContext.Current.Post( OnDownloadCompleted, null );

        });

    }

    public void DownloadAsync(string url) {
        DownloadAsync(url, null);
    }

    private void OnDownloadCompleted(object state) {
        var handler = DownloadCompleted;
        if (handler != null) {
            handler(this, EventArgs.Empty);
        }
    }

    public event EventHandler DownloadCompleted;

}
+1
source

Source: https://habr.com/ru/post/1727995/


All Articles