Last active
September 30, 2020 17:03
-
-
Save Xordal/c4e5804d25246ba81919 to your computer and use it in GitHub Desktop.
TaskBulder for TPL in MVC4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
namespace Utils | |
{ | |
using System.Threading; | |
public interface ITaskBuilder | |
{ | |
TaskBuilder AddTask(Action action); | |
TaskBuilder Run(); | |
} | |
public class TaskBuilder : ITaskBuilder | |
{ | |
private const int MaxWaitHandleWaitAllAllowed = 64; | |
private int waitHandleCount; | |
private ManualResetEventSlim[] mres; | |
private readonly List<Action> taskList; | |
public TaskBuilder() | |
{ | |
waitHandleCount = 0; | |
taskList = new List<Action>(); | |
} | |
/// <summary> | |
/// Add a task | |
/// </summary> | |
/// <param name="action"></param> | |
/// <returns></returns> | |
public TaskBuilder AddTask(Action action) | |
{ | |
taskList.Add(action); | |
waitHandleCount++; | |
return this; | |
} | |
/// <summary> | |
/// Run a batch of tasks | |
/// </summary> | |
/// <returns></returns> | |
public TaskBuilder Run() | |
{ | |
mres = new ManualResetEventSlim[waitHandleCount]; | |
for ( var i = 0; i < mres.Length; i++ ) | |
{ | |
mres[i] = new ManualResetEventSlim( false ); | |
} | |
var index = 0; | |
foreach (var task in taskList) | |
{ | |
int idx = index; | |
Task.Factory.StartNew( task + ( () => this.mres[idx].Set() ) ); | |
index++; | |
} | |
WaitHandle.WaitAll((from x in mres select x.WaitHandle).ToArray()); | |
return this; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DataSet ds1 = null; | |
DataSet ds2 = null; | |
var tb = new TaskBuilder(); | |
tb.AddTask( | |
() => | |
{ | |
ds1 = GetDataSet1(params); | |
}); | |
tb.AddTask( | |
() => | |
{ | |
ds2 = ds1 = GetDataSet2(params); | |
}); | |
tb.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment