Peyman
Peyman

Reputation: 3087

How to pause the code until I want? [something like Thread.Sleep(int);]

I think the best way to make my point is to give you these examples:

Console.ReadLine(); 
Process.WaitForExit();

These functions will pause the application (without freezing the UI).

I need something like this.

In fact, I am writing something like ReadLine() but in windows forms applications.
When you call this method, it should be waited until the user press Enter.

Upvotes: 1

Views: 2646

Answers (5)

Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Most likely, you don't need to halt the execution at all in Windows Forms application.

Windows Forms applications usually require a much more consistent architecture. If you need some code to proceed after the user input, you should not be halting a function execution. In contrast, open a dialog (or provide any other mean for the user to do the required input) and just wait for him to "interact with it". Interaction should raise C# events that will be processed by an logical class instance that knows how to do it and is subscribed to them.

Upvotes: 0

gordy
gordy

Reputation: 9806

Console apps don't have a UI so there's nothing for WaitForExit() to freeze. In a console app the chrome (title bar and window buttons) are handled by the system. In a WinForms app those things aren't painted until you pass the NC_PAINT events to the default handler. If your main message loop is sleeping then your chrome doesn't get painted.

A WinForms app doesn't close automatically so there should be no reason to call something like WaitForExit(). Instead you explicitly tell the app when to close - say when the user presses escape or something.

Upvotes: 1

NoWar
NoWar

Reputation: 37652

Try this

Task logManager = Task.Factory.StartNew(() => {   /* Your code */ }, TaskCreationOptions.LongRunning);

or even

Task screenshotManager; 

     private void StartScreenshotManager()
            {
                screenshotManager = Task.Factory.StartNew(() => { ScreenshotManagerJob(); }, TaskCreationOptions.LongRunning);
                screenshotManager.ContinueWith((t) => { ScreenshotManagerUpdateUI(); }, TaskScheduler.FromCurrentSynchronizationContext());
            }

            private void ScreenshotManagerUpdateUI()
            {
                // ... UI update work here ... 
            }

            private void ScreenshotManagerJob()
            {
             // your code
             }

Upvotes: 0

Sasha
Sasha

Reputation: 8860

You can use backGroundWorker which simply checks for cancellation and waits some time using Thread.Sleep(100) for example.

The other way is to create own thread and control all checks and callbacks yourself.

Upvotes: 1

brunnerh
brunnerh

Reputation: 185445

You can create a thread which does a wait on an AutoResetEvent, the UI thread should continue and accept input which signals the event.

Upvotes: 2

Related Questions