Task, Thread, Events, Action, Func, Pred, Delgates

Markus Freitag 3,791 Reputation points
2022-09-03T18:36:09.717+00:00

Hello,
https://dotnetpattern.com/csharp-action-delegate
https://dotnetpattern.com/csharp-predicate-delegate

I found this.
Maybe you still know good sites or have explanations here. Would be nice.

The main question is
When do I take what? That there is, is already clear.
What are the criteria for the choice?

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-09-04T00:24:41.813+00:00

    I will pick Action and Func,

    Example for Action, we are performing an task in a class which the caller a form, subscribes to the event which adds a string to a ListBox, to prevent cross threading we must use .Invoke.

    The action in the extension method is lb => { listBox2.Items.Add(name);}, in the extension method .Invoke adds the item.

    // in the form  
    public async Task IterateContactNames()  
    {  
    	await foreach (var name in DataOperations.GetAllNamesPaged(true))  
    	{  
    		listBox2.InvokeIfRequired(lb => { listBox2.Items.Add(name);});  
    	}  
    }  
      
    public static class Extensions  
    {  
    	public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : ISynchronizeInvoke  
    	{  
    		if (control.InvokeRequired)  
    		{  
    			control.Invoke(new Action(() => action(control)), null);  
    		}  
    		else  
    		{  
    			action(control);  
    		}  
    	}  
    }  
    

    For Func, a simple example, here we pass in an instance of StudentGrade and return a DTO, StudentEntity, pass in one type below and get another type back,

    public partial class StudentGrade  
    {  
      
    	public static Expression<Func<StudentGrade, StudentEntity>> Projection  
    	{  
    		get  
    		{  
    			return (student) => new StudentEntity()  
    			{  
    				PersonID = student.StudentID,  
    				CourseID = student.CourseID,  
    				FirstName = student.Student.FirstName,  
    				LastName = student.Student.LastName,  
    				Grade = student.Grade  
    			};  
    		}  
    	}  
    }  
    

    All of these Task, Thread, Events, Action, Func, Pred, Delgates are best understood by reading the docs, finding examples and inspecting them. If I were to answer each one in depth this is not the place to do it and can be ad nauseam.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.