graham23s
graham23s

Reputation: 385

Async / Await Task returns no value

What the code does is loops a datagrid of URLs checks in the html for a certain string and returns data accordingly, very basic so far.

I'm trying to understand the await / async methods better, i have a fairly ok grasp so far but i have hit a snag, the code i have so far:

FormMain.cs

        public async Task RunAsyncAnalyzer()
        {
            try
            {
                BtnPerformLinkAnalysis.Enabled = false;
                if (DataGridViewLinks.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in DataGridViewLinks.Rows)
                    {
                        row.Cells[2].Value = await Task.Run(() => { Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });
                    }
                }
                BtnPerformLinkAnalysis.Enabled = true;
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
            }

        }

        private async void BtnPerformLinkAnalysis_Click(object sender, EventArgs e)
        {
            await RunAsyncAnalyzer();
        }

Helpers.cs

        public static string GetLinkPlatformType(string url) {
            string platform_type = "......";
            try { 
                var html = GetWebPageHTML(url);

                if (html.Contains("Start the discussion…")) {
                    platform_type = "DISCUZ|CAN_COMMENT";
                }
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
            }
            return platform_type;
        }

The error i am getting is: cannot convert type 'void' to 'object' and it is on this line: row.Cells[2].Value = await Task.Run(() => { Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });

It also says above it: Awaited Task returns no value but the method GetLinkPlatformType does return a value it is not a void i cannot see what the issue is i know i am over looking something but i'm not entirely sure what, any help in the right direction would be appreciated.

Upvotes: 3

Views: 4912

Answers (1)

devcrp
devcrp

Reputation: 1348

The issue is that your task is not returning anything, you missed the return.

row.Cells[2].Value = await Task.Run(() => { return Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()); });

Otherwise it's just a task that does something but does not return anything.

Also, as @leszek mentioned in the comments, here's another approach:

row.Cells[2].Value = await Task.Run(() => Helpers.GetLinkPlatformType(row.Cells[0].Value.ToString()) );

Hope it helps!

Upvotes: 7

Related Questions