I have web application and it calls different web service to perform different work. Some web services will take long time and some short. Application will call all web services parallel to get result when complete or exception. I have started to write code but i need to know how to implement the following works in the best way.
- A task will be cancelled if any of web service takes more than 5 seconds but remaining tasks will continue to call web service to get either result or excepton.
- I used CancellationTokenSource in my sample code but OperationCanceledException does not catch. It goes to exception catch always.
- Is it best practice to limit number of thread to execute my web services? if so, how can i limit threads and reuse them.
Any sample code or url will help me.
protected async void btnAAC_Click(object sender, EventArgs e)
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(5000);
string[] retResult = null;
Task<string[]> taskResult = Run(cts.Token);
try
{
retResult = await taskResult;
//To do : display data
}
catch (OperationCanceledException ocex)
{
resultsTextBox.Text += "\r\nDownloads canceled.\r\n";
}
catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
}
finally
{
cts.Dispose();
}
}
private async static Task<string[]> Run(CancellationToken cancellationToken)
{
HashSet<Task<string>> tasks = new HashSet<Task<string>>();
List<string> urlList = ServiceManager.SetUpURLList();
List<string> finalResult = new List<string>();
foreach (var work in urlList)
{
tasks.Add(Task.Run(() => DoWork(work, cancellationToken)));
}
try
{
while (tasks.Count > 0)
{
Task<string> finishedTask = await
Task.WhenAny(tasks.ToArray());
tasks.Remove(finishedTask);
finalResult.Add(finishedTask.Result);
}
return finalResult.ToArray();
}
finally
{
//CleanUpAfterWork();
}
}
public async static Task<string> DoWork(string url, CancellationToken cancellationToken)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var html = await Downloader.DownloadHtml(url);
return html;
}
}