Ошибка run task

#android #android-layout #android-gradle-plugin

#Android #android-layout #android-gradle-plugin

Вопрос:

При запуске моего проекта в эмуляторе (AVD) отображается ошибка ‘Run task’. Но когда я очищаю проект без запуска в эмуляторе, эта проблема не видна. Как я могу это решить?

Я провел много интернет-исследований по этому поводу, но, к сожалению, ничего не сработало.

Я сделал слайд «вход» для проекта моей мечты в Android Studio, изначально он был идеальным, без каких-либо ошибок. Когда я попытался запустить это в своем эмуляторе (AVD), отображалась ошибка:

Сборка: сбой сборки >> Запустить сборку >> Запускать задачи >> : приложение: mergerDebugResources >> Выполнить taskAction.

(ПРИМЕЧАНИЕ: >> представляет путь к папке и подпапке, из-за которого произошла ошибка)

Когда я нажал «Сборка: сбой сборки» … на вкладке «Рядом» был показан следующий текст:

Сбой компиляции ресурсов Android C:UsersDELLAndroidStudioProjectsXCityappsrcmainreslayout-v4activity_main.xml:110 : ошибка: неправильно сформированный (недопустимый токен).

Пожалуйста, обратите внимание, что я новичок, у меня нет хорошей идеи о том, как решать такие проблемы ранее.

Еще одна вещь, я открыл проект «hello world» и запустил его, эмулятор открылся и показывает «система процесса не отвечает». Мне нужно запустить мой проект в эмуляторе.

Комментарии:

1. где ваш activity_main.xml и почему даже layout-v4 ??

Ответ №1:

Комментарии:

1. Также отредактируйте токен*

У меня возникла проблема с перехватом исключения из Task.Run, которая была решена путем изменения кода следующим образом. Я хотел бы знать разницу между обработкой исключений двумя способами:

В методе Outside я не могу поймать исключение, но в методе Inside я могу.

void Outside()
{
    try
    {
        Task.Run(() =>
        {
            int z = 0;
            int x = 1 / z;
        });
    }
    catch (Exception exception)
    {
        MessageBox.Show("Outside : " + exception.Message);
    }
}

void Inside()
{
    Task.Run(() =>
    {
        try
        {
            int z = 0;
            int x = 1 / z;
        }
        catch (Exception exception)
        {
            MessageBox.Show("Inside : "+exception.Message);
        }
    });
}

7 ответов

Лучший ответ

Когда задача запускается, любые генерируемые ею исключения сохраняются и повторно генерируются, когда что-то ожидает результата задачи или завершения задачи.

Task.Run() возвращает объект Task, который вы можете использовать для этого, поэтому:

var task = Task.Run(...)

try
{
    task.Wait(); // Rethrows any exception(s).
    ...

Для более новых версий C # вы можете использовать await вместо Task.Wait ():

try
{
    await Task.Run(...);
    ...

Что намного аккуратнее.


Для полноты, вот компилируемое консольное приложение, демонстрирующее использование await:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main()
        {
            test().Wait();
        }

        static async Task test()
        {
            try
            {
                await Task.Run(() => throwsExceptionAfterOneSecond());
            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        static void throwsExceptionAfterOneSecond()
        {
            Thread.Sleep(1000); // Sleep is for illustration only. 
            throw new InvalidOperationException("Ooops");
        }
    }
}


52

Matthew Watson
3 Авг 2017 в 08:41

Основываясь на ответе @MennoJongerius, следующее сохраняет асинхронность и перемещает исключение из .wait в обработчик событий Async Completed:

Public Event AsyncCompleted As AsyncCompletedEventHandler

).ContinueWith(Sub(t)
                   If t.IsFaulted Then
                       Dim evt As AsyncCompletedEventHandler = Me.AsyncCompletedEvent
                       evt?.Invoke(Me, New AsyncCompletedEventArgs(t.Exception, False, Nothing))
                   End If
               End Sub)


-2

David
6 Авг 2020 в 19:32

Для меня я хотел, чтобы мой Task.Run продолжался после ошибки, позволяя пользовательскому интерфейсу обрабатывать ошибку по мере необходимости.

Мое (странное?) Решение — запустить Form.Timer. В моем Task.Run есть очередь (для длительно выполняющихся материалов, не связанных с пользовательским интерфейсом), а у моего Form.Timer есть очередь (для элементов пользовательского интерфейса).

Поскольку этот метод уже работал у меня, было тривиально добавить обработку ошибок: если task.Run получает ошибку, он добавляет информацию об ошибке в очередь Form.Timer, которая отображает диалоговое окно ошибки.


0

Kurtis Lininger
3 Июл 2017 в 21:54

Когда опция «Только мой код» включена, Visual Studio в некоторых случаях прерывает строку, которая вызывает исключение, и отображает сообщение об ошибке, в котором говорится:

Исключение не обрабатывается кодом пользователя.

Это доброкачественная ошибка. Вы можете нажать F5 , чтобы продолжить и увидеть поведение обработки исключений, продемонстрированное в этих примерах. Чтобы Visual Studio не сломалась при первой ошибке, просто снимите флажок «Только мой код» в разделе Инструменты> Параметры> Отладка> Общие .


2

Nastaran Hakimi
24 Мар 2020 в 08:27

Вы можете просто подождать, и тогда исключения всплывут в текущий контекст синхронизации (см. Ответ Мэтью Уотсона). Или, как упоминает Менно Йонгериус, вы можете ContinueWith, чтобы код оставался асинхронным. Обратите внимание, что вы можете сделать это, только если возникнет исключение с помощью параметра продолжения OnlyOnFaulted:

Task.Run(()=> {
    //.... some work....
})
// We could wait now, so we any exceptions are thrown, but that 
// would make the code synchronous. Instead, we continue only if 
// the task fails.
.ContinueWith(t => {
    // This is always true since we ContinueWith OnlyOnFaulted,
    // But we add the condition anyway so resharper doesn't bark.
    if (t.Exception != null)  throw t.Exception;
}, default
     , TaskContinuationOptions.OnlyOnFaulted
     , TaskScheduler.FromCurrentSynchronizationContext());


5

Diego
26 Окт 2018 в 21:03

Во внешнем коде вы проверяете только, не вызывает ли запуск задачи исключение, а не тело задачи. Он выполняется асинхронно, и тогда выполняется код, который его инициировал.

Ты можешь использовать:

void Outside()
{
    try
    {
        Task.Run(() =>
        {
            int z = 0;
            int x = 1 / z;
        }).GetAwaiter().GetResult();
    }
    catch (Exception exception)
    {
        MessageBox.Show("Outside : " + exception.Message);
    }
}

Использование .GetAwaiter().GetResult() ожидает завершения задачи и передает выброшенное исключение как есть и не помещает их в AggregateException.


5

michal.jakubeczy
23 Фев 2018 в 12:03

Идея использования Task.Wait сработает, но заставит вызывающий поток (как говорит код) ждать и, следовательно, блокировать, пока задача не будет завершена, что фактически делает код синхронным, а не асинхронным.

Вместо этого используйте параметр Task.ContinueWith для достижения результатов:

Task.Run(() =>
{
   //do some work
}).ContinueWith((t) =>
{
   if (t.IsFaulted) throw t.Exception;
   if (t.IsCompleted) //optionally do some work);
});

Если задача должна продолжаться в потоке пользовательского интерфейса, используйте параметр TaskScheduler.FromCurrentSynchronizationContext () в качестве параметра для продолжения следующим образом:

).ContinueWith((t) =>
{
    if (t.IsFaulted) throw t.Exception;
    if (t.IsCompleted) //optionally do some work);
}, TaskScheduler.FromCurrentSynchronizationContext());

Этот код просто повторно выбросит совокупное исключение с уровня задачи. Конечно, вы также можете ввести здесь другую форму обработки исключений.


60

Wheelie
28 Июн 2019 в 08:05

0 / 0 / 0

Регистрация: 11.04.2018

Сообщений: 6

1

10.05.2018, 12:26. Показов 5166. Ответов 3


Студворк — интернет-сервис помощи студентам

Task не содержит определение для Run. Что делать?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

10.05.2018, 12:26

3

Эксперт .NET

11480 / 7823 / 1192

Регистрация: 21.01.2016

Сообщений: 29,333

10.05.2018, 12:53

2

Влад3, посмотреть ещё раз.



0



Администратор

Эксперт .NET

15621 / 12590 / 4990

Регистрация: 17.03.2014

Сообщений: 25,584

Записей в блоге: 1

10.05.2018, 12:59

3

Лучший ответ Сообщение было отмечено Влад3 как решение

Решение

Влад3, он был добавлен в .NET 4.5. Переключи проект на более новую версию .NET



2



0 / 0 / 0

Регистрация: 11.04.2018

Сообщений: 6

10.05.2018, 13:01

 [ТС]

4

OwenGlendower, спасибо, помогло.



0



I have a very simple custom Task.Run() method.
Using the .net Task.Run() method works fine, the custom method does not execute the action.

Any ideas?

What I have tried:

Usage:

      Task.Run(() => TestTasks.CustomTasks.DummyTask());

      
      TestHelpers.Tasks.Run(TestTasks.CustomTasks.DummyTask);

Code:

namespace TestHelpers
{
    public static class Tasks
    {
        public static string Run(Action action)
        {
            try
            {
                Task.Run(() => action);
                return "ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }
    }
}

namespace TestTasks
{
    public static class CustomTasks
    {
        public static void DummyTask()
        {
            for (int i = 0; i < 10; i++)
                System.Threading.Thread.Sleep(100);
        }
    }
}

Updated 18-Feb-19 22:55pm


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

April 27, 2019

Kill Tasks and handle Exceptions

Tasks and Exceptions (C#.NET)

Check out the basic article about Tasks and Async if you haven’t already.

To Infinity… and Beyond!

Now to get into some serious parallelism. Imagine we have a list of projects that all need to be processed in some way AND we want to calculate pi (once). We can do that… with our old friend ContinueWith and a List<Task<Task>>:

//starting by creating a collection of tasks that we need to keep track of...
var tasks = new List<Task<Task>>()
foreach(Project p in projectList){
    tasks.Add(Renderer.GaussianMapAsync(p.newdata)
        .ContinueWith((rendering)=>{
            p.rendering = rendering;
            ProjectDAL.SaveAsync(p);
        )
    );
}
//below code will run simultaneously to above
var pi = slowPiCalculator(40000);
//wait for ALLL the tasks to finish:
foreach(Task<Task> tt in tasks){
    await await tt;
}

The above is NOT great code. It will do the job, sure, but man it is ugly.

Here’s a better solution taking advantage of LINQ and async lambdas.

var tasks = projectList.Select(async (p)=>{
    p.rendering = await Renderer.GaussianMapAsync(p.newdata);
    await ProjectDAL.SaveAsync(p);
});
var pi = slowPiCalculator(40000);
await Task.WhenAll(tasks);

Even though the above is neater, consider if a lambda is necessary — C#7 introduced inline functions, which can sometimes help readability without exposing a function to the rest of the class in the way a new private method would:

async Task renderAndSaveAsync(Project p) {
    p.rendering = await Renderer.GaussianMapAsync(p.newdata);
    await ProjectDAL.SaveAsync(p);
}
var tasks = projectList.Select(renderAndSaveAsync)
var pi = slowPiCalculator(40000);
await Task.WhenAll(tasks);

What happens if there’s an exception?

If there is an exception inside a Task, the exception will not be thrown until you «await» the task.

You can absolutely await a task inside a try block and catch the exception of the task. You can also check if a Task has «Faulted» (i.e. will throw an exception on await) by checking out it’s «Status» property, and retrieve it’s exception by

  • awaiting the Task and capturing the exception or
  • reading the «Exception» property of the Task.

Awaiting on Task.WhenAll will cause an AggregateException to be thrown if any of the tasks in the WhenAll list have an exception to throw.


Note

ContinueWith() will still trigger if an exception occurs in the Task it continues.

If any task waited on with WhenAll() throws an exception, WhenAll() will still wait for all other tasks to complete (or fault) before it throws the AggregateException.


How To Stop Running Tasks

Task.Run can accept a cancellation token as part of it’s argument list. On the surface of it, this promises to cancel a running task if we ask it to… but it doesn’t.

Calling cancel() on the CancellationTokenSource for the token you pass to Task.Run will not cancel the task for you. CancellationTokenSource/CancellationToken’s only job is to provide a thread-safe construct for you to check if a cancellation was called.

Because WhenAll will not throw it’s exception until all Tasks have completed, we can’t simply wrap a try/catch around the WhenAll call and cancel the token if there is an exception. This becomes the responsibility of each Task being run.

Here is an example on how to use CancellationToken to stop all Tasks when any the database throws an exception.

async Task renderAndSaveAsync(Project p, CancellationTokenSource tokenSource) {
    try{
		p.rendering = await Renderer.GaussianMapAsync(p.newdata, token);
    	await ProjectDAL.SaveAsync(p, token);
	}
	catch{
		tokenSource.cancel();
	}
}
decimal slowPiCalculator(int limit, CancellationToken tokenSource)
    => 2 + 2 / piWorker(limit,1, tokenSource);

decimal piWorker(int limit, decimal start, CancellationToken tokensource){
    if(tokensource.token.IsCancellationRequested){
        tokensource.token.ThrowIfCancellationRequested();
    }
    if(limit===0){
        return start;
    }
   try{
    return 1 + 1 / (1 / (start) + piWorker(limit-1, start+1, token));
   }
   catch{
        tokensource.Cancel();
        throw;
   }
}
var canceller = new CancellationTokenSource();
List<Task> tasks = projectList.Select(
    (p) => Task.Run(renderAndSaveAsync(p, canceller), canceller.Token) );
Task<string> piTask = Task.Run(
    ()=>slowPiCalculator(40000, canceller.Token), canceller.Token);
tasks.Add(piTask);
string pi = null;
try
{
    await Task.WhenAll(tasks);
    pi = await piTask;
}
catch
{
    throw;	//most likely an AggregateException containing
            //one or more InnerExceptions from some of the Tasks in list.
            //calling cancel here would only trigger once all Tasks complete.
}

In above example, if we needed to rollback the database changes, we could do so by constructing a single transaction around the WhenAll and passing the transaction through to the renderAndSaveAsync database methods.

I wish there was a nicer way to get Tasks to cancel themselves. The above method is an infuriatingly manual process, but at least the lack of a black box does make the behaviour clear.

The method of calculating pi is based on Thomas J. Pickett and Ann Coleman’s continued fraction published in American Mathematical Monthly (2008).

Понравилась статья? Поделить с друзьями:
  • Ошибка run out of memory
  • Ошибка rufus при загрузке
  • Ошибка rtsuvc sys
  • Ошибка rtc error
  • Ошибка rtl100 bpl