Вопрос по .net, c# – Самый простой способ сделать огонь и забыть метод в C #?

123

Error: User Rate Limit Exceeded[OperationContract(IsOneWay = true)]Error: User Rate Limit ExceededMethodFoo(){}Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

class Foo
{
    static void Main()
    {
        FireAway(); //No callback, just go away
        Console.WriteLine("Happens immediately");
    }

    static void FireAway()
    {
        System.Threading.Thread.Sleep(5000);
        Console.WriteLine("5 seconds later");
    }
}

NBError: User Rate Limit ExceededError: User Rate Limit Exceeded)

Ваш Ответ

9   ответов
10

QueueBackgroundWorkItem

public static class BackgroundTaskRunner
{     
    public static void FireAndForgetTask(Action action)
    {
        HostingEnvironment.QueueBackgroundWorkItem(cancellationToken => // .Net 4.5.2 required
        {
            try
            {
                action();
            }
            catch (Exception e)
            {
                // TODO: handle exception
            }
        });
    }

    /// <summary>
    /// Using async
    /// </summary>
    public static void FireAndForgetTask(Func<Task> action)
    {
        HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken => // .Net 4.5.2 required
        {
            try
            {
                await action();
            }
            catch (Exception e)
            {
                // TODO: handle exception
            }
        });
    }
}

BackgroundTaskRunner.FireAndForgetTask(() =>
{
    FireAway();
});

BackgroundTaskRunner.FireAndForgetTask(async () =>
{
    await FireAway();
});

Error: User Rate Limit Exceeded
34

Task.Factory.StartNew(() => FireAway());

Or even...

Task.Factory.StartNew(FireAway);

Or...

new Task(FireAway).Start();

Where FireAway is

public static void FireAway()
{
    // Blah...
}

So by virtue of class and method name terseness this beats the threadpool version by between six and nineteen characters depending on the one you choose :)

ThreadPool.QueueUserWorkItem(o => FireAway());
Error: User Rate Limit Exceededstackoverflow.com/help/referencingError: User Rate Limit Exceeded
Error: User Rate Limit ExceededTask.Factory.StartNew(() => FireAway(foo));.
Error: User Rate Limit ExceededTask.Factory.StartNew(() => FireAway(foo));Error: User Rate Limit ExceededhereError: User Rate Limit Exceededhere
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededFireAway?
234
ThreadPool.QueueUserWorkItem(o => FireAway());

Error: User Rate Limit Exceeded

Task.Run(() => FireAway());

Error: User Rate Limit ExceededError: User Rate Limit Exceeded.

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded(new Action(FireAway)).BeginInvoke()
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededTask.Factory.StartNew(() => myevent());Error: User Rate Limit Exceededstackoverflow.com/questions/14858261/…
1

Error: User Rate Limit Exceeded

Task.Run(FireAway);

Error: User Rate Limit Exceeded

2

static void Main(string[] args)
{
      new MethodInvoker(FireAway).BeginInvoke(null, null);

      Console.WriteLine("Main: " + Thread.CurrentThread.ManagedThreadId);

      Thread.Sleep(5000);
}

private static void FireAway()
{
    Thread.Sleep(2000);

    Console.WriteLine("FireAway: " + Thread.CurrentThread.ManagedThreadId );  
}
Error: User Rate Limit ExceededTask.Run()Error: User Rate Limit Exceeded
13

(new Thread(() => { 
    FireAway(); 
    MessageBox.Show("FireAway Finished!"); 
}) { 
    Name = "Long Running Work Thread (FireAway Call)",
    Priority = ThreadPriority.BelowNormal 
}).Start();

enter image description here

Error: User Rate Limit Exceeded
15

Error: User Rate Limit Exceeded

Task.Run(() => FireAway());
Error: User Rate Limit ExceededTask.Factory.StartNew(() => FireAway(), CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);Error: User Rate Limit Exceededblogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx
Error: User Rate Limit Exceeded
16

AutoResetEventWaitHandle

Using System;
Using System.Threading;

class Foo
{
    static AutoResetEvent autoEvent = new AutoResetEvent(false);

    static void Main()
    {
        ThreadPoolQueueUserWorkItem(new WaitCallback(FireAway), autoEvent);
        autoEvent.WaitOne(); // Will wait for thread to complete
    }

    static void FireAway(object stateInfo)
    {
        System.Threading.Thread.Sleep(5000);
        Console.WriteLine("5 seconds later");
        ((AutoResetEvent)stateInfo).Set();
    }
}
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
7

Error: User Rate Limit Exceededmsdn.microsoft.com/en-us/library/0b1bf3y3(v=vs.90).aspx
Error: User Rate Limit ExceededBeginInvokeError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Похожие вопросы