This method is called from wpf main thread. Throwing - Cannot implicitly convert type 'bool' to 'System.Threading.Tasks.Task' error. What am I doing wrong? DocCollection is of type ObservableCollection.
Task TaskProcesQueue(SynchronizationContext _SyncContext)
{
return Task.Run(() =>
{
if (DocCollection != null)
{
foreach (var item in DocCollection.ToList())
{
ProcessCurrentDocument(item);
var t = Task.Run(() => DocCollection.Remove(item), _SyncContext));
}
}
});
}
Task.Run
has no overload accepting a SynchronizationContext
. Hence, when overload resolution kicks in, it fails to find the appropriate overload. If you remove the synchronization context, it compiles:
var t = Task.Run(() => DocCollection.Remove(item));
Note i'd advise you not to use a dedicated threadpool thread to remove an item from a collection. That seems redundant. Instead, let the thread-pool thread already dedicated to removing items to it's job:
while (DocCollection.Count > 0)
{
ProcessCurrentDocument(item);
DocCollection.Remove(item);
}
Edit:
If you want to post on the SynchronizationContext
:
_SyncContext.Post(_ => { DocCollection.Remove(item) }, null);
Now that your code is in sync, your problem is that DocCollection.Remove(item)
is actually returning true/false, being a boolean method that indicates whether or not the remove succeeded or not.
If you'll remove that whole line, all will work nicely, and items will be processed (but not removed).
I think what you want is to actually use the Result of the running the task (note that it'll block though).
Have a look at the official page on MSDN for more.
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.