本文整理汇总了C#中TaskFactory类的典型用法代码示例。如果您正苦于以下问题:C# TaskFactory类的具体用法?C# TaskFactory怎么用?C# TaskFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TaskFactory类属于命名空间,在下文中一共展示了TaskFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Begin_Click
private void Begin_Click(object sender, EventArgs e)
{
Begin.Text = "开始...";
Begin.Enabled = false;
start = true;
List<Task> listTask = new List<Task>();
TaskFactory tskf = new TaskFactory();
var controls = groupBox.Controls;
foreach (var control in controls)
{
if (control.GetType() != typeof(Label))
{
continue;
}
var label = control as Label;
listTask.Add(tskf.StartNew(new Action(() =>
{
while (start)
{
Thread.Sleep(200);
var text = GeNum(label);
UpdateLabl(label, text);
//Console.WriteLine("label:[{0}],value:[{1}]", label.Name, text);
}
})));
}
tskf.ContinueWhenAll(listTask.ToArray(), (rest) => { ShowMessage(); });
//MessageBox.Show("主线程结束了。。。", "结果");
Thread.Sleep(1000);
End.Enabled = true;
}
示例2: HtmlSearchManager
public HtmlSearchManager(string text, string url, int threadNumber)
{
_textToSearch = text;
_url = url;
_taskLimit = new LimitedConcurrencyLevelTaskScheduler(threadNumber);
_taskFactory = new TaskFactory(_taskLimit);
}
示例3: TestUIModel
/// <summary>
/// Creates an instance.
/// </summary>
protected TestUIModel(TaskFactory uiThread)
{
// Initialize members
UIThread = uiThread;
InputEnabled = true;
_output = new StringBuilder();
}
示例4: CMS
static CMS()
{
Cache = new Cache();
AppSetting = new AppSettings();
Constants = new Constants();
UiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
}
示例5: Main
static void Main()
{
const int numberTasks = 2;
const int partitionSize = 1000000;
var data = new List<string>(FillData(partitionSize * numberTasks));
var barrier = new Barrier(numberTasks + 1);
var taskFactory = new TaskFactory();
var tasks = new Task<int[]>[numberTasks];
for (int i = 0; i < numberTasks; i++)
{
tasks[i] = taskFactory.StartNew<int[]>(CalculationInTask,
Tuple.Create(i, partitionSize, barrier, data));
}
barrier.SignalAndWait();
var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) =>
{
return c1 + c2;
});
char ch = 'a';
int sum = 0;
foreach (var x in resultCollection)
{
Console.WriteLine("{0}, count: {1}", ch++, x);
sum += x;
}
Console.WriteLine("main finished {0}", sum);
Console.WriteLine("remaining {0}, phase {1}", barrier.ParticipantsRemaining, barrier.CurrentPhaseNumber);
}
示例6: Run
public static void Run()
{
Console.WriteLine(@"Task Factory Example: Start");
var parent = Task.Run(() =>
{
var results = new Int32[3];
var taskFactory = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);
taskFactory.StartNew(() => results[0] = 0);
taskFactory.StartNew(() => results[1] = 1);
taskFactory.StartNew(() => results[2] = 2);
return results;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (var i in parentTask.Result)
{
Console.WriteLine(i);
}
});
finalTask.Wait();
Console.WriteLine(@"Task Factory Example: Stop");
}
示例7: Start
public void Start()
{
if (this.listener.IsListening)
throw new ArgumentException("already listening");
this.listener.Start();
Log.Message($"Web server started at {url}");
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
TaskFactory taskFactory = new TaskFactory(token, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
this.listenerTask = taskFactory.StartNew(() => {
while (!token.IsCancellationRequested) {
var context = this.listener.GetContextAsync();
var httpRequest = context.Result.Request;
var request = new WebHookRequest() {Request = HttpRequestParser.Extract(httpRequest)};
this.requests.Enqueue(request);
var response = context.Result.Response;
response.StatusCode = 200;
var message = System.Text.Encoding.UTF8.GetBytes("OK");
response.ContentLength64 = message.Length;
response.ContentType = "text";
var outputstream = response.OutputStream;
outputstream.Write(message, 0, message.Length);
outputstream.Close();
}
}, token);
}
示例8: RCInputTestUIModel
/// <summary>
/// Creates an instance.
/// </summary>
public RCInputTestUIModel(TaskFactory uiThread)
: base(uiThread)
{
// Initialize device
Device = new NavioRCInputDevice();
Device.ChannelsChanged += OnChannelsChanged;
}
示例9: HeartRateViewModel
public HeartRateViewModel( IHeartRateService heartRateService )
{
_uiFactory = new TaskFactory( TaskScheduler.FromCurrentSynchronizationContext() );
_heartRateService = heartRateService;
RegisterEvents();
}
示例10: CountableThreadPool
public CountableThreadPool(int threadNum = 5)
{
_maxDegreeOfParallelism = threadNum;
_maxTaskCount = _maxDegreeOfParallelism + threadNum;
LimitedConcurrencyLevelTaskScheduler lcts = new LimitedConcurrencyLevelTaskScheduler(threadNum);
_factory = new TaskFactory(lcts);
Task.Factory.StartNew(() =>
{
while (true)
{
if (_end)
{
break;
}
lock (_tasks)
{
var finishedTasks = _tasks.Where(t => t.IsCompleted).ToList();
foreach (var finishedTask in finishedTasks)
{
_tasks.Remove(finishedTask);
}
Thread.Sleep(100);
}
}
});
}
示例11: Consumer
public Consumer(string id, string groupName, ConsumerSetting setting)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (groupName == null)
{
throw new ArgumentNullException("groupName");
}
Id = id;
GroupName = groupName;
Setting = setting ?? new ConsumerSetting();
_lockObject = new object();
_subscriptionTopics = new List<string>();
_topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
_pullRequestQueue = new BlockingCollection<PullRequest>(new ConcurrentQueue<PullRequest>());
_pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
_consumingMessageQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>());
_messageRetryQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>());
_handlingMessageDict = new ConcurrentDictionary<long, ConsumingMessage>();
_taskIds = new List<int>();
_taskFactory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(Setting.ConsumeThreadMaxCount));
_remotingClient = new SocketRemotingClient(Setting.BrokerConsumerIPEndPoint, null, this);
_binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
_scheduleService = ObjectContainer.Resolve<IScheduleService>();
_allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
_executePullRequestWorker = new Worker("Consumer.ExecutePullRequest", ExecutePullRequest);
_handleMessageWorker = new Worker("Consumer.HandleMessage", HandleMessage);
_logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
_waitSocketConnectHandle = new AutoResetEvent(false);
}
示例12: HtmlSearchManager_ver2
public HtmlSearchManager_ver2(string startUrl, string textToSearch, int numberOfUrlsToSearch)
{
_startUrl = startUrl;
_textToSearch = textToSearch;
_numberOfUrlsToSearch = numberOfUrlsToSearch;
_taskFactory = new TaskFactory(_th_limit);
}
示例13: WorldViewModel
public WorldViewModel()
{
_uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
_uiFactory = new TaskFactory(_uiScheduler);
Tools = new OrderingCollection<ITool, IOrderMetadata>(t => t.Metadata.Order);
CompositionTarget.Rendering += CompTargetRender;
}
示例14: OnNavigatedTo
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
loadingProgressRing.IsActive = true;
try
{
if (Constants.RecUriDic.Count == 0 && Constants.CategoryNameList.Count == 0)
{
try
{
DataServiceQuery<CATEGORY> cateDsq = (DataServiceQuery<CATEGORY>)(from cate in ctx.CATEGORY
select cate);
TaskFactory<IEnumerable<CATEGORY>> tfc = new TaskFactory<IEnumerable<CATEGORY>>();
IEnumerable<CATEGORY> categories = await tfc.FromAsync(cateDsq.BeginExecute(null, null), iar => cateDsq.EndExecute(iar));
foreach (var c in categories)
{
Constants.CategoryNameList.Add(c.CATE_NAME);
}
}
catch
{
ShowMessageDialog("categories!");
}
try
{
DataServiceQuery<RECOMMENDATION> craDsq = (DataServiceQuery<RECOMMENDATION>)(from re in ctx.RECOMMENDATION
select re);
TaskFactory<IEnumerable<RECOMMENDATION>> tf = new TaskFactory<IEnumerable<RECOMMENDATION>>();
IEnumerable<RECOMMENDATION> recommendation = await tf.FromAsync(craDsq.BeginExecute(null, null), iar => craDsq.EndExecute(iar));
foreach (var r in recommendation)
{
Constants.RecUriDic.Add(r.TITLE, r.ICON_URL);
}
}
catch
{
ShowMessageDialog("recommedations!");
}
}
}
catch
{
ShowMessageDialog("On nav to");
}
courseDsq = (DataServiceQuery<COURSE_AVAIL>)(from course_avail in ctx.COURSE_AVAIL select course_avail);
courseDsq.BeginExecute(OnCourseAvailComplete, null);
UserProfileBt.DataContext = Constants.User;
//UserProfileBt.IsEnabled = false;
}
示例15: Consumer
public Consumer(string groupName, ConsumerSetting setting)
{
if (groupName == null)
{
throw new ArgumentNullException("groupName");
}
GroupName = groupName;
Setting = setting ?? new ConsumerSetting();
_lockObject = new object();
_subscriptionTopics = new Dictionary<string, HashSet<string>>();
_topicQueuesDict = new ConcurrentDictionary<string, IList<MessageQueue>>();
_pullRequestQueue = new BlockingCollection<PullRequest>(new ConcurrentQueue<PullRequest>());
_pullRequestDict = new ConcurrentDictionary<string, PullRequest>();
_messageRetryQueue = new BlockingCollection<ConsumingMessage>(new ConcurrentQueue<ConsumingMessage>());
_taskFactory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(Setting.ConsumeThreadMaxCount));
_remotingClient = new SocketRemotingClient(Setting.BrokerAddress, Setting.SocketSetting, Setting.LocalAddress);
_adminRemotingClient = new SocketRemotingClient(Setting.BrokerAdminAddress, Setting.SocketSetting, Setting.LocalAdminAddress);
_binarySerializer = ObjectContainer.Resolve<IBinarySerializer>();
_scheduleService = ObjectContainer.Resolve<IScheduleService>();
_allocateMessageQueueStragegy = ObjectContainer.Resolve<IAllocateMessageQueueStrategy>();
_executePullRequestWorker = new Worker("ExecutePullRequest", ExecutePullRequest);
_logger = ObjectContainer.Resolve<ILoggerFactory>().Create(GetType().FullName);
_remotingClient.RegisterConnectionEventListener(new ConnectionEventListener(this));
}