Перезапуск потока в .NET (с использованием C #)

+ означает один или несколько предыдущих атомов. ({1,})

* означает ноль или более. Это не может сравниться ни с чем, кроме символов, указанных в выражении с квадратной скобкой. ({0,})

Обратите внимание, что + доступен в расширенных и Perl-совместимых регулярных выражениях и недоступен в Basic RE. * доступен во всех трех диалектах RE. Этот диалект, который вы используете, зависит, скорее всего, от того, на каком языке вы находитесь.

В основном, в современных операционных системах, которые по-прежнему по умолчанию для BRE, используются только grep и sed (оба которые имеют возможность ERE в качестве опции) и non-vim vi.

13
задан drowneath 28 June 2009 в 13:14
поделиться

6 ответов

Simply add MyThread = new Thread(MyFunction) before calling MyThread.Start() in doStart(). Do not create the thread outside of your methods, the space there is thought for declarations.

EDIT: Please note that killing a thread with thread.Abort() can be very dangerous. You should try to accomplish clean multithreading, like Groo described in his post.

17
ответ дан 1 December 2019 в 17:27
поделиться

Once you have aborted your thread, you cannot start it again.

But your actual problem is that you are aborting your thread. You should never use Thread.Abort().

If your thread should be paused and continued several times, you should consider using other mechanisms (like AutoResetEvent, for example).

[EDIT]

The simplest solution to abort a thread, as mentioned by Ian Griffiths in the link above, is:

The approach I always recommend is dead simple. Have a volatile bool field that is visible both to your worker thread and your UI thread. If the user clicks cancel, set this flag. Meanwhile, on your worker thread, test the flag from time to time. If you see it get set, stop what you're doing.

The only thing that you need to do to make it work properly, is to rearrange your background method so that it runs in a loop - so that you can periodically check if your flag has been set by a different thread.

If you need to have pause and resume functionality for the same worker thread, instead of the simple volatile bool flag approach, you could go for a slightly more complex approach, a synchronizing construct such as AutoResetEvent. These classes also provide a way to put the worker thread to sleep for a specified (or indefinite) amount of time between signals from the non-worker thread.

This thread contains a concrete example with Start, Pause, Resume and Stop methods. Note how Brannon's example never aborts the thread. It only fires an event, and then waits until the thread finishes gracefully.

34
ответ дан 1 December 2019 в 17:27
поделиться

Простой ответ: вы не можете. Как только поток был прерван, вы не можете перезапустить его. Просто создайте метод или что-то, что возвращает объект Thread именно так, как вам нужно. Когда вам понадобится новый поток, просто получите его с помощью этого метода.

7
ответ дан 1 December 2019 в 17:27
поделиться

Нет, нет, но зачем вам это нужно? Просто запустите новый поток с тем же ThreadStart и тем же параметром (если есть).

2
ответ дан 1 December 2019 в 17:27
поделиться

If you really need to interrupt the thread function and resume, you should set a condition and then check it periodically during processing.

That would allow you to stop processing for some amount of time and then resume.

I've used events and Wait calls to accomplish a similar task.

0
ответ дан 1 December 2019 в 17:27
поделиться

The easiest way is to not abort the thread.

0
ответ дан 1 December 2019 в 17:27
поделиться
Другие вопросы по тегам:

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