加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 异步编程控制流程

发布时间:2020-12-15 08:14:04 所属栏目:百科 来源:网络整理
导读:我在过去2天一直在阅读有关c#异步方法的内容,根据我的理解,与线程(threadpool.queueuserworkitem())不同,对异步方法的调用不会立即返回,只有在被调用的方法命中时才会返回等待或完成(或例外) 请参阅以下示例. public partial class MainWindow : Window{ //
我在过去2天一直在阅读有关c#异步方法的内容,根据我的理解,与线程(threadpool.queueuserworkitem())不同,对异步方法的调用不会立即返回,只有在被调用的方法命中时才会返回等待或完成(或例外)

请参阅以下示例.

public partial class MainWindow : Window
{
    // . . .
    private async void startButton_Click(object sender,RoutedEventArgs e)
    {
        // ONE
        Task<int> getLengthTask = AccessTheWebAsync();

        // FOUR
        int contentLength = await getLengthTask;

        // SIX
        resultsTextBox.Text +=
            String.Format("rnLength of the downloaded string: {0}.rn",contentLength);
    }


    async Task<int> AccessTheWebAsync()
    {
        // TWO
        HttpClient client = new HttpClient();
        Task<string> getStringTask =
            client.GetStringAsync("http://msdn.microsoft.com");

        // THREE                 
        string urlContents = await getStringTask;

        // FIVE
        return urlContents.Length;
    }
}

根据我收集的内容,在上面的代码中,AccessTheWebAsync()被同步调用(即,在调用时,控件不会立即返回).但是在名为“THREE”的行中,运行时将返回控件.

我的问题是:

>运行时如何决定何时使用线程池或何时在调用线程中运行任务? (即执行代码而不返回控制)
>在上面的代码中,将使用新线程(或线程池)?
>如果AccessTheWebAsync()执行计算密集型操作,例如运行具有无数次迭代的循环,则控件将仅在循环完成时返回到调用者.是对的吗?
>在异步函数中,有没有办法立即返回控件,然后继续在后台线程中执行工作? (就像我们调用threadpool.queueuserworkitem())
>在没有await的情况下调用异步方法(假设它可能)与调用非异步方法相同吗?

解决方法

首先重要的是:如果要等待的任务尚未完成,则运行时将仅在等待时返回到调用者.

问题1:我在这里引用MSDN:

The async and await keywords don’t cause additional threads to be created. Async methods don’t require multithreading because an async method doesn’t run on its own thread.

Source

问题2:可能在GetStringAsync的实现中,但我们不知道,我们也不必知道它.这足以让我们知道GetStringAsync以某种方式得到它的结果而不会阻塞我们的线程.

问题3:如果循环放在await关键字之前,是的.

问题4:引用与以前相同的段落:

You can use Task.Run to move CPU-bound work to a background thread

您不需要async和await关键字.例:

private Task<int> DoSomethingAsync()
{
    return Task.Run(() =>
    {
        // Do CPU heavy calculation here. It will be executed in the thread pool.
        return 1 + 1;
    });
}

问题5:我会再次引用

An async method typically contains one or more occurrences of an await operator,but the absence of await expressions doesn’t cause a compiler error. If an async method doesn’t use an await operator to mark a suspension point,the method executes as a synchronous method does,despite the async modifier. The compiler issues a warning for such methods.

Source(和以前一样,只是一个不同的部分)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读