c#multithreading发出3个不同的线程

时间:2022-09-01 21:02:31

I had a recent question about this however I am now getting an error which is "Cannot assign void to an implicitly-typed local variable". The part underlined is the declaration of var Results.

我最近有一个关于这个的问题但是我现在得到的错误是“无法将void分配给隐式类型的局部变量”。下划线部分是var结果的声明。

All I am trying to do is send out these 3 different methods at the same time as they are all data work and will take some time. I figured asynchronously sending them out and then waiting for the return of the 3 parts would work best. Each method returns a datatable, and I am just trying to access what comes back.

我所要做的就是同时发送这3种不同的方法,因为它们都是数据工作,需要一些时间。我想异步发送它们然后等待3个部分的返回将是最好的。每个方法都返回一个数据表,我只是想尝试访问返回的内容。

Can anyone please point me in the right direction?

有谁能指出我正确的方向?

 async void Main(string[] args)
    {
        // need instance, virtual methods, may add overrides. 
        SchoolData CSD = new SchoolData();
        FData FD = new FData();
        GiftData GD = new GiftData();


        List<Task> tasks = new List<Task>();
        tasks.Add(Task.Run(() => CSD.getSchool()));
        tasks.Add(Task.Run(() => FD.getF()));
        tasks.Add(Task.Run(() => GD.getGift()));

        var Results = await Task.WhenAll(tasks);
}

1 个解决方案

#1


You'll want to have a List<Task<DataTable>> since your tasks all compute DataTables. As it is you're storing (non-generic) Task objects, meaning they aren't representing any results.

您将需要一个List >,因为您的任务都计算DataTables。因为它是存储(非泛型)Task对象,这意味着它们不代表任何结果。

You'll also need to move the code into another method besides Main as it cannot be marked as async.

除了Main之外,您还需要将代码移动到另一种方法,因为它不能标记为异步。

#1


You'll want to have a List<Task<DataTable>> since your tasks all compute DataTables. As it is you're storing (non-generic) Task objects, meaning they aren't representing any results.

您将需要一个List >,因为您的任务都计算DataTables。因为它是存储(非泛型)Task对象,这意味着它们不代表任何结果。

You'll also need to move the code into another method besides Main as it cannot be marked as async.

除了Main之外,您还需要将代码移动到另一种方法,因为它不能标记为异步。