简体   繁体   English

通过使用委托异步调用方法的最佳实践吗?

[英]Is it a best practice to call methods asynchronously by using delegates?

This msdn article is entitled "How to call a Visual C# method asynchronously" . 此msdn文章的标题为“如何异步调用Visual C#方法”

The article says "Asynchronous calls are made by using delegates" to which I reply in my head "not necessarily, that's only one way to do it". 文章说:“异步调用是通过使用委托进行的”,我脑海中对此回答:“不一定,这只是一种实现方式”。

The matter-of-fact tone of the articles statement makes me wonder - Is it a best practice, or does MS consider it a best practice, to use delegates when making asynchronous calls? 文章陈述的实质内容使我感到奇怪-在进行异步调用时使用委托是一种最佳实践,还是MS认为是一种最佳实践?

Up to the current .NET version, asynchronous methods have typically been handled in separate background threads from the one you trigger them from, so it's been mostly essential to do it using a delegate that you can invoke in another thread. 直到当前的.NET版本,异步方法通常都在与您触发它们的后台线程分开的独立后台线程中进行处理,因此使用可在另一个线程中调用的委托来进行异步处理非常重要。

However, with the recent C# Async CTP (which will probably be in C# 5.0 or another future version), the story is changed a little - it's not essential to use delegates, you can write code in a traditional imperative style, and the compiler will do most of the work for you. 但是,对于最近的C#异步CTP(可能会在C#5.0或其他将来的版本中),情况有所变化-使用委托不是必需的,您可以采用传统的命令式风格编写代码,编译器将为您完成大部分工作。 This might involve delegates, but not necessarily - the compiler does some clever tricks and writes a finite state machine which can be used to execute code asynchronously. 这可能涉及委托,但不是必须的-编译器做了一些巧妙的技巧,并编写了一个可用于异步执行代码的有限状态机。

Yes, delegates are the way to call methods asynchronously . 是的,委托是异步调用方法的方式 It is not best practice, that is how it is done. 这不是最佳做法,而是这样做的。 In .NET, you must use a delegate. 在.NET中,您必须使用委托。

Somebody can tell me im wrong please but i've been under the impression at compile time a delegate is as good as a method, the purpose of a delegate being a signature definition. 有人可以告诉我我是错的,但是我在编译时给人的印象是委托和方法一样好,委托的目的是签名定义。 I can think of no other way of executing async code without a method even if its anonymous which becomes a method at compile time.. 我想不出没有方法就可以执行异步代码的其他方法,即使它的匿名名称在编译时变成了方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM