【问题标题】:In C# 5, difference between async function and non-async function? [duplicate]在 C# 5 中,异步函数和非异步函数的区别? [复制]
【发布时间】:2014-08-13 17:06:40
【问题描述】:

假设我有以下代码:

static void Main(string[] args)
{
    println("begin s");
    Task<int> s = CaculateSometingAsync();
    println("begin s1");
    Task<int> s1 = CaculateSometingAsync1();

    println(s.Result.ToString());
    println(s1.Result.ToString());
}

static async Task<int> CaculateSometingAsync()
{

    return await Task.Factory.StartNew<int>(() =>
    {
        Thread.Sleep(1000);
        return 100;
    });
}

static Task<int> CaculateSometingAsync1()
{

    return Task.Factory.StartNew<int>(() =>
    {
        Thread.Sleep(1000);
        return 200;
    });

}

结果如下:

16:55:38 begin s
16:55:38 begin s1
16:55:39 100
16:55:39 200

我对这两个函数的了解是它们具有相同的行为。 他们都创建了一个线程池线程来运行任务。

两者

Task<int> s = CaculateSometingAsync();

Task<int> s1 = CaculateSometingAsync1();

不要阻塞主线程。

那么这两个函数有什么区别吗?

【问题讨论】:

    标签: c# multithreading asynchronous parallel-processing


    【解决方案1】:

    不同之处在于您使用它的方式。 在第一个 (CaculateSometingAsync) 中,您将其声明为异步,然后在其中等待直到完成。然后你返回它返回的任何东西。

    在您的第二个 (CaculateSometingAsync1) 中,您只是将其用作一种“即发即弃”的东西,因此它会消失、等待并直接返回到您调用它的位置。

    (以及为什么你使用println 方法来打印字符串?:))

    【讨论】:

      【解决方案2】:

      您在 CaculateSometingAsync 中等待,但可以在 s 上等待,因为该方法被声明为异步,而您无法在 s1 上等待,因为 CaculateSometingAsync1 未声明为异步。您使用关键字的方式意味着bahviour没有区别

      【讨论】:

        猜你喜欢
        • 2019-05-01
        • 2022-11-16
        • 1970-01-01
        • 2020-03-09
        • 2013-07-12
        • 1970-01-01
        • 2021-11-18
        • 2021-11-07
        • 1970-01-01
        相关资源
        最近更新 更多