Hands-On Parallel Programming with C# 8 and .NET Core 3 by Shakti Tanwar

Hands-On Parallel Programming with C# 8 and .NET Core 3 by Shakti Tanwar

Author:Shakti Tanwar [Shakti Tanwar]
Language: eng
Format: epub
Tags: COM051470 - COMPUTERS / Programming Languages / ASP .NET, COM051310 - COMPUTERS / Programming Languages / C#, COM051240 - COMPUTERS / Software Development and Engineering / Systems Analysis and Design
Publisher: Packt
Published: 2019-12-20T06:25:07+00:00


WaitAny: Blocks the calling thread until it receives a signal from any of the wait handles it's waiting for.

The following is the signature of the WaitAny method:

public static int WaitAny (System.Threading.WaitHandle[] waitHandles);

Here is an example that makes use of two threads to perform an item search. Both threads will execute in parallel and the program waits for any of the threads to finish execution at the WaitHandle.WaitAny(waitHandles) method before printing the item index to the console.

We have two methods, binary search and linear search, that perform a search using binary and linear algorithms. We want to get a result as soon as possible from either of these methods. We can achieve this via signaling using AutoResetEvent and store the results in the findIndex and winnerAlgo global variables:

static int findIndex = -1;

static string winnerAlgo = string.Empty;

private static void BinarySearch(object state)

{

dynamic data = state;

int[] x = data.Range;

int valueToFind = data.ItemToFind;

AutoResetEvent autoResetEvent = data.WaitHandle

as AutoResetEvent;

//Search for item using .NET framework built in Binary Search

int foundIndex = Array.BinarySearch(x, valueToFind);

//store the result globally

Interlocked.CompareExchange(ref findIndex, foundIndex, -1);

Interlocked.CompareExchange(ref winnerAlgo, "BinarySearch",

string.Empty);

//Signal event

autoResetEvent.Set();

}



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.