我对async / await做错了什么?

时间:2014-07-28 23:39:40

标签: c# multithreading async-await

我正致力于创建一个基本上为我玩游戏的应用程序。它形成突袭,加入突袭,然后启动突袭。我试图异步完成这一切。

一些背景:FormRaidAsync,JoinRaidAsync和LaunchRaidAsync都会发出Web请求。方法本身也设置为异步,但是当我运行程序时,它只加入大约2-3个帐户/秒。

我做错了什么,或async / await不一定在新线程上运行每个请求?如果是这种情况,我如何调整此代码以接近10 /秒的速率加入帐户?我是否必须使用其他形式的多线程来同时发出更多请求?

谢谢大家。如果需要更详细的信息,请告诉我。

public async Task<string> StartRaidAsync()
{
    string raid_id = String.Empty;

    try
    {
        raid_id = await this.Helper.FormRaidAsync(this.TargetRaid.Id, this.Former.Id, this.TargetRaid.IsBossRaid).ConfigureAwait(false);
        Console.WriteLine("Formed raid with {0}.", this.Former.Name);

        List<Task> joinTasks = new List<Task>();

        foreach (var joiner in this.Joiners)
        {
            try
            {
                joinTasks.Add(this.Helper.JoinRaidAsync(raid_id, joiner.Id));
            }
            catch (Exception)   // Not sure which exceptions to catch yet.
            {
                Console.WriteLine("Error joining {0}. Skipped.", joiner.Name);
            }
        }

        Task.WaitAll(joinTasks.ToArray());

        await this.Helper.LaunchRaidAsync(raid_id, this.Former.Id).ConfigureAwait(false);
        Console.WriteLine("{0} launched raid.", this.Former.Name);
    }
    catch (Exception)   // Not sure which exceptions to catch yet.
    {
        return "ERROR";
    }

    return raid_id;
}

在JoinRaidAsync中:

public async Task JoinRaidAsync(string raid_id, string suid)
{
    var postUrl = "some url";
    var postData = "some data";

    await this.Socket.PostAsync(postUrl, postData).ConfigureAwait(false);
    Console.WriteLine("Joined {0}.", suid);
}

Inside Socket.PostAsync:

public async Task<string> PostAsync(string url, string postData)
{
    return await SendRequestAsync(url, postData).ConfigureAwait(false);
}

内部SendRequestAsync:

protected virtual async Task<string> SendRequestAsync(string url, string postData)
{
    for (int i = 0; i < 3; i++)
    {
        try
        {
            HttpWebRequest request = this.CreateRequest(url);

            if (!String.IsNullOrWhiteSpace(postData))
            {
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                var stream = await request.GetRequestStreamAsync().ConfigureAwait(false);

                using (StreamWriter writer = new StreamWriter(stream))
                {
                    await writer.WriteAsync(postData).ConfigureAwait(false);
                    await writer.FlushAsync().ConfigureAwait(false);
                }
            }

            using (HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync().ConfigureAwait(false)))
            {
                string responseString = String.Empty;

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    responseString = await reader.ReadToEndAsync().ConfigureAwait(false);
                }

                return responseString;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

    return String.Empty;
}

1 个答案:

答案 0 :(得分:5)

  

我做错了什么,或async / await不一定在新线程上运行每个请求?

async / await不会创建新主题。

  

如果是这种情况,我如何调整此代码以接近10 /秒的速度加入帐户?

异步代码可以一次执行多个请求。当然,这些请求的速度取决于Web服务调用的速度。

我现在在代码中唯一看错的是混合阻塞和异步代码。替换:

Task.WaitAll(joinTasks.ToArray());

使用:

await Task.WhenAll(joinTasks.ToArray());

如果您仍然遇到问题,可能是由于您的网络服务或其他支持代码(例如JoinRaidAsync中的代码)。