Share via


Cannot convert lambda expression to type 'System.Threading.Tasks.Task'

Question

Thursday, April 24, 2014 3:01 PM

I got an exception "Cannot convert lambda expression to type 'System.Threading.Tasks.Task' because it is not a delegate type"

My code:

 public async Task RunScript()
        {
            var semaphore = new SemaphoreSlim(2);
            var pendingTasks = new HashSet<Task>();
            var syncLock = new Object();
            Action<Task> queueTaskAsync = async (task) =>
            {
                lock (syncLock)
                    pendingTasks.Add(task);

                await semaphore.WaitAsync().ConfigureAwait(false);
                try
                {
                    await task;
                }
                catch
                {
                    if (!task.IsCanceled && !task.IsFaulted)
                        throw;
                    // the error will be observed later, 
                    // keep the task in the list
                    return;
                }
                finally
                {
                    semaphore.Release();
                }

                // remove successfully completed task from the list
                lock (syncLock)
                    pendingTasks.Remove(task);
            };

            foreach (var workItem in MyQueue.GetConsumingEnumerable())
            {
         // error is here
                queueTaskAsync(async () =>
                {
                    await PlayMessage(workItem);
                    Thread.Sleep(500);
                });
            }

            await Task.WhenAll(pendingTasks.ToArray());
        }

Thanks for help.

All replies (2)

Thursday, April 24, 2014 3:45 PM âś…Answered

Hi, you can try this:

queueTaskAsync(Task.Run(async () =>
                {
                    await PlayMessage(workItem);
                    Thread.Sleep(500);
                }));

Tuesday, June 20, 2017 12:06 PM

Hi there, this works, but with this solution the task does not own the UI (wpf). You will have exception if inside the task you do something like TextBlock.Text = "hi". Any workaround? Thank you