简体   繁体   中英

Running parallel tasks c#

In a windows store app project i have a function that i call several times inside a foreach cycle to fill in some objects

The method header looks like this

private async Task createInvite(JsonValue item, string meetingid, List<MeetingInvitee> listInvitees)

i was trying to run this in parallel tasks like so

List<Task> ts = new List<Task>();
foreach (JsonValue item in invitees)
{
    ts.Add(createInvite(item, meetingid, listInvitees));
}

await Task.WhenAll(ts);

but it seems it doesnt create tasks that run at all at same time. this takes about 10 seconds.

if instead i use this

//List<Task> ts = new List<Task>();
foreach (JsonValue item in invitees)
{
    //ts.Add(createInvite(item, meetingid, listInvitees));
      await createInvite(item, meetingid, listInvitees);
}

//await Task.WhenAll(ts);

it also takes about 10 seconds.

Am i not running several tasks at same time with my first option?

Edit

private async Task createInvite(JsonValue item, string meetingid, List<MeetingInvitee> listInvitees)
{
    try
    {

        Stopwatch st = Stopwatch.StartNew();
        MeetingInvitee org = new MeetingInvitee();
        MeetingInvitee altorg = new MeetingInvitee();
        JsonObject invitee2;
        JsonObject invitee;
        InviteeDB InviteeForDB = new InviteeDB();
        GappService gappservice = new GappService();

        MeetingInvitee inv = new MeetingInvitee();


        JsonObject.TryParse(item.Stringify(), out invitee2);

        invitee = invitee2["user"].GetObject();



        if (invitee2.ContainsKey("_id"))
        {
            inv.id = invitee2["_id"].GetString();
            InviteeForDB.Id = invitee2["_id"].GetString();
        }
        else
        {
            InviteeForDB.Id = invitee2["user"].GetString();
        }

        if (invitee2.ContainsKey("status"))
        {
            if (invitee2["status"].ValueType == JsonValueType.Null)
            {
                inv.status = string.Empty;
                InviteeForDB.Status = string.Empty;
            }
            else
            {
                inv.status = invitee2["status"].GetString();
                InviteeForDB.Status = invitee2["status"].GetString();
            }
        }
        Stopwatch st2 = Stopwatch.StartNew();
        if (invitee2.ContainsKey("user"))
        {

            if (invitee2["user"].ValueType != JsonValueType.Null)
            {
                User iUser = new User();
                //iUser.Id = InviteeForDB.UserID;

                JsonSerializerSettings sett = new JsonSerializerSettings();
                sett.NullValueHandling = NullValueHandling.Ignore;
                iUser = JsonConvert.DeserializeObject<User>(invitee.Stringify(), sett);

                inv.user = iUser;
            }
            else
                return;
        }
        else
            return;

        InviteeForDB.MeetingID = meetingid;
        ds.inviteeRepository.Add(InviteeForDB);
        listInvitees.Add(inv);
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}

Your code isn't actually async (it has no await statements), so all of the work is happening in initial createInvite() call inside the for loop.

You can make that actually run in parallel using Parallel.ForEach() , but that will break your code, because it isn't actually thread-safe.

There is nothing truly async about your method. Simply adding the async modifier doesn't magically make this async, or execute in parallel which is what I think you're trying to do. All it does is signal the compiler that a state-machine needs to be generated. This code, as is, will execute completely synchronously.

You can explicitly invoke your method on a thread-pool thread using Task.Run or Parallel.ForEach , but looking at your code it doesn't look as if it would be thread-safe at all to do that. Before going any further, try to isolate CreateInvite to actually be thread-safe, then look into one of the options mentioned above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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