Your scenario like ConcerentQueue without bounding. So you don't need to use CompleteAdding:
// Initialize Q and Cancelleation Token
var q = new BlockingCollection<int>();
var cts = new CancellationTokenSource();
var ct = cts.Token;
// Producer Thread.
var t1 = Task.Run(() =>
{
int i = 0;
do
{
q.Add(++i);
Console.WriteLine(i + " is added to q");
}
while (!ct.IsCancellationRequested);
Console.WriteLine("producer task is canceled");
}, ct);
// Consumer Thread.
var t2 = Task.Run(() =>
{
do
{
while(q.Count > 0)
{
var result = q.Take();
Console.WriteLine(result + " is removed from q");
}
}
while (!ct.IsCancellationRequested);
Console.WriteLine("consumer task is canceled");
}, ct);
To see in action, create a console app and copy the above code in the main function:
using System;
using System.Threading;
using System.Collections.Concurrent;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Copy above code here
Console.Title = "Press any key to exit";
Console.ReadLine();
Console.Title = "Wait to Queue get empty";
// Cancel t1 & t2
cts.Cancel();
// Wait for both thread to done
Task.WaitAll(t1, t2);
}
}
}
See this example for using CompleteAdding.
I need the whole code of the Endless function. Could you share the code and translate the error into English? Which version of .Net are you using?
Hello,
The XAML
@Markus Freitag The error said your Endless method is not async. when you marked a method as async you need at least have an await statement in the body method.
Replace Task.WaitAll(t1, t2); to below code:
Hello,
the code. Thanks in advance for your help.
I can't post the code here. Reason for picture.
Return value is wrong
Hello,
//private async Task BtnListEndless_Click(object sender, RoutedEventArgs e)
@Markus Freitag
There is no reason to set the return value of BtnListEndless_ClickAsync to Task, this event handler will not return information to any place, maybe you should set it to async void.
By the way, when you need to add information, it is best to add it to the original question, and then post a comment to remind members that you have made changes.
@Markus Freitag
If the Endless method just start two tasks, no need for async in the Endless signature.
Can you make a sample with C# WPF desktop application?
When I need async?
Can you make a sample with C# WPF desktop application?
When I need async?
@Markus Freitag We are going off the grid. I will provide you with an example, but please ask it in a different question. Also, remove unrelated comments here and mark the answer as accepted if it answers your first question. Don't forget to tag me in your next question.
Sign in to comment
0 additional answers
Sort by: Most helpful