异步或并行任务-C# [英] Async or parallel tasks - C#

查看:47
本文介绍了异步或并行任务-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要执行两个I/O任务的应用程序:获取GPS位置,通过蓝牙检索一些数据.两项任务的完成时间可能会有所不同,并且可能需要花费几秒钟的时间.为了提高应用程序的速度,我想同时启动两个活动,然后等待两个活动都完成,然后再继续.

I have an application where I need to do two I/O tasks: get a GPS location, retrieve some data over Bluetooth. Both tasks can vary in time to complete, and can take many seconds. To improve the speed of the application I want to kick-off both activities at the same time, and then wait for both to complete before proceeding.

如果我这样做:

bool locationStatus= await GetCurrentLocation();
bool vehicleStatus = await GetVehicleData();

第二个功能会启动吗,还是仅UI未被阻止?

does the second function get kicked off, or is it only the UI that is not blocked?

我需要调用并行任务吗?

Do I need to invoke parallel tasks instead?

推荐答案

您正在直接等待第一个功能.如果要让函数完成异步操作,则必须将await放在需要变量的位置.

You are directly awaiting the first function. If you want to let the functions complete asynchronous, you will have to put the await at the position where you need the variables.

例如:

var locationStatus = GetCurrentLocation();
var vehicleStatus = GetVehicleData();

if (await locationStatus && await vehicleStatus)
{
    // Do stuff
}

这篇关于异步或并行任务-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆