本文整理汇总了C#中System.Threading.Tasks.Task.Start方法的典型用法代码示例。如果您正苦于以下问题:C# Task.Start方法的具体用法?C# Task.Start怎么用?C# Task.Start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Tasks.Task
的用法示例。
在下文中一共展示了Task.Start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnBeginRequest
private static void OnBeginRequest(object sender, EventArgs e) {
var context = (HttpApplication)sender;
// TaskCreationOptions.PreferFairness 를 지정해야, StartNew() 메소드를 바로 시작한다.
var stopwatchTask
= new Task<Lazy<double>>(() => {
var sw = new Stopwatch();
sw.Start();
if(IsDebugEnabled) {
var request = context.Request;
log.Debug(BeginRequestLogFormat,
request.UserHostAddress,
request.RequestType,
request.CurrentExecutionFilePath);
}
// Lazy 값을 처음 호출할 때, stop watch가 끝나고, 경과 값을 반환한다.
return new Lazy<double>(() => {
sw.Stop();
return sw.ElapsedMilliseconds;
});
});
stopwatchTask.Start();
Local.Data[AsyncAccessLogModuleKey] = stopwatchTask;
}
示例2: Main
static void Main(string[] args)
{
// create the first generation task
Task firstGen = new Task(() => {
Console.WriteLine("Message from first generation task");
// comment out this line to stop the fault
throw new Exception();
});
// create the second generation task - only to run on exception
Task secondGen1 = firstGen.ContinueWith(antecedent => {
// write out a message with the antecedent exception
Console.WriteLine("Antecedent task faulted with type: {0}",
antecedent.Exception.GetType());
}, TaskContinuationOptions.OnlyOnFaulted);
// create the second generation task - only to run on no exception
Task secondGen2 = firstGen.ContinueWith(antecedent => {
Console.WriteLine("Antecedent task NOT faulted");
}, TaskContinuationOptions.NotOnFaulted);
// start the first generation task
firstGen.Start();
// wait for input before exiting
Console.WriteLine("Press enter to finish");
Console.ReadLine();
}
示例3: CommandProcessor
public CommandProcessor(ICommandProcessingStrategy processingStrategy,
ICommandQueue commandQueue)
{
_processingStrategy = processingStrategy;
_commandQueue = commandQueue;
_cancellationTokenSource = new CancellationTokenSource();
var token = _cancellationTokenSource.Token;
var task = new Task(
() =>
{
while (!token.IsCancellationRequested)
{
var cmd = _commandQueue.Dequeue();
while (cmd != null)
{
_processingStrategy.ProcessCommand(cmd.Execute);
cmd = commandQueue.Dequeue();
}
Thread.Sleep(100);
}
},
token,
TaskCreationOptions.LongRunning);
task.Start();
}
示例4: Validate
public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent)
{
var tasks = new List<Task<IYubicoResponse>>();
var cancellation = new CancellationTokenSource();
foreach (var url in urls)
{
var thisUrl = url;
var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token);
task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
tasks.Add(task);
task.Start();
}
while (tasks.Count != 0)
{
// TODO: handle exceptions from the verify task. Better to be able to propagate cause for error.
var completed = Task.WaitAny(tasks.Cast<Task>().ToArray());
var task = tasks[completed];
tasks.Remove(task);
if (task.Result != null)
{
cancellation.Cancel();
return task.Result;
}
}
return null;
}
示例5: RunTestLoop
private void RunTestLoop(int numberOfTasks, TaskScheduler[] schedulers)
{
var taskList = new List<Task>(numberOfTasks);
for (int i = 0; i < numberOfTasks; i++)
{
int id = i; // capture
Task t = new Task(() =>
{
if (Verbose) Console.WriteLine("Task: " + id);
});
if (schedulers == null || schedulers.Length == 0)
{
t.Start();
}
else
{
var scheduler = schedulers[i % schedulers.Length];
t.Start(scheduler);
}
taskList.Add(t);
}
Task.WaitAll(taskList.ToArray());
}
示例6: Task
void ICallSequence.Enqueue(Action action)
{
Interlocked.Increment(ref _counters.Enqueue);
var next = new Task(() => invoke(action));
var prev = Interlocked.Exchange(ref _tail, next);
if (prev == null)
{
next.Start();
return;
}
prev.ContinueWith(x => next.Start());
}
示例7: AsincronismoConTpl
/// <summary>
/// Implementación para la demostración del flujo de control de invocaciones
/// a través de elementos de programa de TPL.
/// </summary>
/// <returns>Resultado de la operación asincrónica.</returns>
private Task AsincronismoConTpl()
{
var tareaCompuesta = new Task(() =>
{
Task<string> tarea1 = ObtenerInfoThreadAsync("TPL No. 1");
tarea1.ContinueWith(tarea =>
{
Console.WriteLine(tarea1.Result);
Task<string> tarea2 = ObtenerInfoThreadAsync("TPL No. 2");
tarea2.ContinueWith(tareaAnidada =>
Console.WriteLine(tareaAnidada.Result),
TaskContinuationOptions.NotOnFaulted |
TaskContinuationOptions.AttachedToParent);
tarea2.ContinueWith(tareaAnidada =>
Console.WriteLine(tareaAnidada.Exception.InnerException),
TaskContinuationOptions.OnlyOnFaulted |
TaskContinuationOptions.AttachedToParent);
},
TaskContinuationOptions.NotOnFaulted |
TaskContinuationOptions.AttachedToParent);
tarea1.ContinueWith(tarea =>
Console.WriteLine(tarea1.Exception.InnerException),
TaskContinuationOptions.OnlyOnFaulted |
TaskContinuationOptions.AttachedToParent);
});
tareaCompuesta.Start();
return tareaCompuesta;
}
示例8: Start
public void Start()
{
_source = new CancellationTokenSource();
var token = _source.Token;
_listenerTask = new Task(() =>
{
BusListener.MessageReceivedEvent += (s, e) => Console.WriteLine("Received message at " + e.Endpoint + " of type " + e.MessageType);
BusListener.MessageSentEvent += (s, e) => Console.WriteLine("Sent message " + e.MessageType);
BusListener.BusStartedEvent += (s, e) => Console.WriteLine("Bus started " + e.Endpoint);
BusListener.MessageExceptionEvent += (s, e) => Console.WriteLine("Exception with message " + e.Endpoint + " for type " + e.MessageType + " with value " + e.Exception);
using (var host = new ServiceHost(_listener, new[] { new Uri("net.tcp://localhost:5050") }))
{
host.AddServiceEndpoint(typeof(IBusListener), new NetTcpBinding(), "NServiceBus.Diagnostics");
host.Opened += (s, e) => Console.WriteLine("Listening for events...");
host.Closed += (s, e) => Console.WriteLine("Closed listening for events...");
host.Open();
while (!token.IsCancellationRequested) { }
host.Close();
}
}, token);
_listenerTask.Start();
_listenerTask.Wait(10000);
}
示例9: CreateRemoteThread
public Task CreateRemoteThread(MemoryWriter writer)
{
UIntPtr bytesWriten;
Win32.WriteProcessMemory(processInfo.hProcess, writer.TargetStartAddress, writer.Buffer,
(uint)writer.Size, out bytesWriten);
//lastWin32Error = Marshal.GetLastWin32Error();
Win32.FlushInstructionCache(processInfo.hProcess, writer.TargetStartAddress, new UIntPtr((uint)writer.Size));
//lastWin32Error = Marshal.GetLastWin32Error();
IntPtr hThread = Win32.CreateRemoteThread(processInfo.hProcess, IntPtr.Zero, 0, writer.CodeTargetStartAddress,
IntPtr.Zero, 0, IntPtr.Zero);
//lastWin32Error = Marshal.GetLastWin32Error();
Task task = new Task(() =>
{
Win32.WaitForSingleObject(hThread, Win32.INFINITE);
// Free the memory in the process that we allocated
Win32.VirtualFreeEx(processInfo.hProcess, writer.TargetStartAddress, 0, Win32.FreeType.Release);
});
task.Start();
return task;
}
示例10: MultiRunGPUGravityModel
public MultiRunGPUGravityModel(int length, Action<float> progressCallback = null, float epsilon = 0.8f, int maxIterations = 100)
{
var programPath = Assembly.GetEntryAssembly().CodeBase.Replace( "file:///", String.Empty );
try
{
this.gpu = new GPU();
}
catch
{
throw new XTMFRuntimeException( "Unable to create a connection to the GPU, please make sure you are using a DirectX11+ card!" );
}
Task initialize = new Task( delegate()
{
this.length = length;
this.ProgressCallback = progressCallback;
this.Epsilon = epsilon;
this.MaxIterations = maxIterations;
CreateBuffers();
} );
initialize.Start();
// while everything else is being initialized, compile the shader
this.gravityModelShader = gpu.CompileComputeShader( Path.Combine( Path.GetDirectoryName( programPath ), "Modules", "GravityModel.hlsl" ), "CSMain" );
initialize.Wait();
if ( this.gravityModelShader == null )
{
throw new XTMFRuntimeException( "Unable to compile GravityModel.hlsl!" );
}
}
示例11: Main
static void Main()
{
try
{
var tester = new OpenKeyValTester();
var t = new Task(async () =>
{
await tester.RunTests();
});
t.Start();
t.Wait();
Console.WriteLine("Done.");
Console.ReadLine();
}
catch (WebException we)
{
Console.WriteLine("WebException: Message");
Console.WriteLine(we.Message);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Exception:");
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
示例12: CloseMayOverrideAsync
protected override async Task CloseMayOverrideAsync()
{
var dbM = _dbManager;
if (dbM != null)
{
await dbM.CloseAsync().ConfigureAwait(false);
dbM.Dispose();
}
_dbManager = null;
Task closeFolders = new Task(delegate
{
Parallel.ForEach(_folders, new ParallelOptions() { MaxDegreeOfParallelism = 4 }, folder =>
{
folder?.Dispose(); // LOLLO NOTE avoid async calls within a Parallel.ForEach coz they are not awaited
});
});
Task save = SaveNonDbPropertiesAsync();
closeFolders.Start();
await Task.WhenAll(closeFolders, save).ConfigureAwait(false);
await RunInUiThreadAsync(delegate
{
_folders.Clear();
}).ConfigureAwait(false);
}
示例13: Main
static void Main(string[] args)
{
TwangManSays("********************************************");
TwangManSays("* HANG THE TWANG *");
TwangManSays("********************************************");
CurrentGames = new Dictionary<long, TwitterThread>();
tweetsToSend = new ConcurrentQueue<SendArgs>();
TwitterSender = new Task(DoWork);
TwitterSender.Start();
_sendService = new TwitterService(Authentication.ConsumerKey, Authentication.ConsumerSecret);
_sendService.AuthenticateWith(Authentication.AccessToken, Authentication.AccessTokenSecret);
_service = new TwitterService(Authentication.ConsumerKey, Authentication.ConsumerSecret);
_service.AuthenticateWith(Authentication.AccessToken, Authentication.AccessTokenSecret);
TwitterListener = new Task(Listen);
TwitterListener.Start();
Console.ReadLine();
_service.CancelStreaming();
}
示例14: CreateSubscription
public void CreateSubscription(ServiceBusEnpointData value) {
//TODO determine how we can change the filters for an existing registered item
logger.Log(LogLevel.Info, "CreateSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3}", value.SubscriptionName, value.DeclaredType.ToString(), value.MessageType.ToString(), value.IsReusable);
SubscriptionDescription desc = null;
var data = value.MessageType.FullName;
if (!namespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName)) {
logger.Log(LogLevel.Info, "CreateSubscription Creating {0}", value.SubscriptionName);
var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
Helpers.Execute(() => {
desc = namespaceManager.CreateSubscription(topic.Path, value.SubscriptionName, filter);
});
}
else {
logger.Log(LogLevel.Info, "CreateSubscription Exists {0}", value.SubscriptionName);
desc = namespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
}
SubscriptionClient subscriptionClient = factory.CreateSubscriptionClient(topic.Path, value.SubscriptionName, ReceiveMode.PeekLock);
var state = new AzureBusReceiverState() {
Client = subscriptionClient,
EndPointData = value,
Subscription = desc
};
mappings.Add(state);
Task t = new Task(ProcessMessagesForSubscription, state);
t.Start();
}
示例15: When_saving_two_aggregates_in_parallel
public When_saving_two_aggregates_in_parallel()
{
_testStore = new TestInMemoryEventStore();
_rep1 = new CacheRepository(new Repository(_testStore), _testStore, new MemoryCache());
_aggregate1 = new TestAggregate(Guid.NewGuid());
_aggregate2 = new TestAggregate(Guid.NewGuid());
_rep1.Save(_aggregate1);
_rep1.Save(_aggregate2);
var t1 = new Task(() =>
{
for (var i = 0; i < 100; i++)
{
var aggregate = _rep1.Get<TestAggregate>(_aggregate1.Id);
aggregate.DoSomething();
_rep1.Save(aggregate);
}
});
var t2 = new Task(() =>
{
for (var i = 0; i < 100; i++)
{
var aggregate = _rep1.Get<TestAggregate>(_aggregate2.Id);
aggregate.DoSomething();
_rep1.Save(aggregate);
}
});
t1.Start();
t2.Start();
Task.WaitAll(t1, t2);
}