سؤال

I have something like this:

private void DoSomething()
{
    System.Console.WriteLine("Creating Foo");
    Foo result = new Foo();

    DoSomethingAsync();

    System.Console.WriteLine("Returning Foo");
    return result;
}


private async void DoSomethingAsync()
{
    // The following task takes a long time, but is not CPU intensive
    await TaskEx.Run(() =>
    {
         // code lives here... removed for this example
    });
}

Since I don't hit the CPU much, I don't need a thread. What can I use instead of Run to avoid the creation of a thread?

هل كانت مفيدة؟

المحلول

I think you're misunderstanding the intent of the Task Asynchrony Pattern here. What you're doing is probably better handled by ThreadPool.QueueUserWorkItem which will reuse a worker thread from the process's pool, only creating one if necessary.

The TAP allows you to break a task into "chunks" of work that can be processed incrementally, but it does not directly provide a means to say "this is a background task".

نصائح أخرى

It depends on the task that you're doing. Since you say that it doesn't use a lot of CPU, I'll assume the task takes a long time because it's waiting for other events. So, you'll need to design your task to register callbacks for those events, where each callback completes quickly on the main thread, but isn't triggered until the event you're awaiting actually occurs.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top