en-UShe-IL
You are here:   Blog
Register   |  Login

Blog Archive:

Maximize
* Can be used in order to search for older blogs Entries

Search in blogs


Blog Categories:

Maximize
* Can be used in order to search for blogs Entries by Categories

Blog Tags:

Maximize
* Can be used in order to search for blogs by keywords

TNWikiSummit


Awared MVP

 


Microsoft® Community Contributor 


Microsoft® Community Contributor


 Read this before you use the blog! Maximize

Recent Entries

Minimize
ינו13

Written by: ronen ariely
13/01/2011 13:00 RssIcon

ניהול משימות – Threads Managing

מושגים, רקע ודוגמאות

Queue

אוסף עם ייחודיות וסדר קבוע.

עובד בשיטת "נכנס ראשון יוצא ראשון"

* המחיר בשימוש ב Queue גדול הוא משאבי מחשב.

Thread

משימת עיבוד הקטנה ביותר הניתנת לתזמון על ידי מערכת ההפעלה.

 

 

ThreadPool

מצבור Threads המאורגנים בתוך Queue.

ברגע שמסתיים Thread נשלחת אל ה Queue הודעה ונשלף ממנו ה Thread הבא לביצוע.

ThreadPool מאפשר שימוש במטפלי HTTP (handlers) בעבודה א-סינכרונית. המשימה שאמורה להיות מבוצעת עם החזרת האינפורמציה מהפנייה נכנסת ל Queue של ThreadPool עד שמגיעה תגובה מהמשימה החיצונית.

http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx

Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

[HostProtectionAttribute(

    SecurityAction.LinkDemand

    , Synchronization = true

    , ExternalThreading = true

)]

public static class ThreadPool

 

דוגמה בסיסית:

* הדוגמה לקוחה מאתר מייקרוסופט לצורך המדריכון

using System;
using System.Threading;
public class Example {
    public static void Main() {
        // Queue the task.
        // נגדיר אובייקט
        // WaitCallback
        // חדש במפעיל את הפרוצדורה
        // ThreadProc
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
 
        Console.WriteLine(
            "Main thread does some work, then sleeps."
        );
        // If you comment out the Sleep, the main thread exits before
        // the thread pool task runs.  
        // The thread pool uses background threads,
        // which do not keep the application running.  
        // (This is a simple example of a race condition.)
        Thread.Sleep(1000);
 
        Console.WriteLine("Main thread exits.");
    }
    
    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) {
        // No state object was passed to QueueUserWorkItem, so 
        // stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}

 

דוגמה לשימוש בפנייה א-סינכרונית:

* הדוגמה לקוחה מאתר מייקרוסופט לצורך המדריכון

using System;
using System.Web;
using System.Threading;
 
class HelloWorldAsyncHandler : IHttpAsyncHandler
{
    public bool IsReusable { get { return false; } }
 
    public HelloWorldAsyncHandler()
    {
    }
 
    public IAsyncResult BeginProcessRequest(
        HttpContext context, AsyncCallback cb, Object extraData)
    {
        context.Response.Write(
            "

Begin IsThreadPoolThread is "

 +
            Thread.CurrentThread.IsThreadPoolThread +
            "

\r\n"
        );
        AsynchOperation asynch = 
                new AsynchOperation(cb, context, extraData);
        asynch.StartAsyncWork();
        return asynch;
    }
 
    public void EndProcessRequest(IAsyncResult result)
    {
    }
 
    public void ProcessRequest(HttpContext context)
    {
        throw new InvalidOperationException();
    }
}
 
class AsynchOperation : IAsyncResult
{
    private bool _completed;
    private Object _state;
    private AsyncCallback _callback;
    private HttpContext _context;
 
    bool IAsyncResult.IsCompleted { 
        get { return _completed; } }
    WaitHandle IAsyncResult.AsyncWaitHandle { 
        get { return null; } }
    Object IAsyncResult.AsyncState { 
        get { return _state; } }
    bool IAsyncResult.CompletedSynchronously { 
        get { return false; } }
 
    public AsynchOperation(
        AsyncCallback callback
        , HttpContext context
        , Object state)
    {
        _callback = callback;
        _context = context;
        _state = state;
        _completed = false;
    }
 
    public void StartAsyncWork()
    {
        ThreadPool.QueueUserWorkItem
            (new WaitCallback(StartAsyncTask), null);
    }
 
    private void StartAsyncTask(Object workItemState)
    {
 
        _context.Response.Write(
            "

Completion IsThreadPoolThread is "

 
            + Thread.CurrentThread.IsThreadPoolThread 
            + "

 

\r\n"
);
 
        _context.Response.Write(
            "Hello World from Async Handler!");
        _completed = true;
        _callback(this);
    }
}

 

 קישורים נוספים:

מדריך נהדר ברמה גבוהה בקובץ PDF להורדה