The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.

The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.

Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.

    • C# 1.0 with Visual Studio.NET

    • C# 2.0 with Visual Studio 2005

    • C# 3.0 with Visual Studio 2008

    • C# 4.0 with Visual Studio 2010

    • C# 5.0 with Visual Studio 2012

    • C# 6.0 with Visual Studio 2015

    • C# 7.0 with Visual Studio 2017






    These are the versions of C# known about at the time of this writing:

    • C# 1.0 released with .NET 1.0 and VS2002 (January 2002)
    • C# 1.2 (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call Dispose on IEnumerators which implemented IDisposable. A few other small features.
    • C# 2.0 released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, iterator blocks
    • C# 3.0 released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), query expressions
    • C# 4.0 released with .NET 4 and VS2010 (April 2010). Major new features: late binding (dynamic), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parameters
    • C# 5.0 released with .NET 4.5 and VS2012 (August 2012). Major features: async programming, caller info attributes. Breaking change: loop variable closure.
    • C# 6.0 released with .NET 4.6 and VS2015 (July 2015). Implemented by Roslyn. Features: initializers for automatically implemented properties, using directives to import static members, exception filters, element initializers, await in catch and finally, extension Add methods in collection initializers.
    • C# 7.0 released with .NET 4.7 and VS2017 (March 2017) Major new features: tuples, ref locals and ref return, pattern matching (including pattern-based switch statements), inline outparameter declarations, local functions, binary literals, digit separators, and arbitrary async returns.
    • C# 7.1 released with VS2017 v15.3 (August 2017) Minor new features: async maintuple member name inferencedefault expressionpattern matching with generics.
    • C# 7.2 released with VS2017 v15.5 (November 2017) Minor new features: private protected access modifierSpan<T>, aka interior pointer, aka stackonly structeverything else.

    There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version property still reports 4.0.xxx.

    More detailed information about the relationship between the language, runtime and framework versions is available on the C# in Depth site. This includes information about which features of C# 3.0 you can use when targeting .NET 2.0. (If anyone wants to bring all of the content into this wiki answer, they're welcome to.)

    As of May 3, 2017, the C# Language Team created a history of C# versions and features on their github repo: Features Added in C# Language Versions





    Mutex 클래스 

    Mutex 클래스는 Monitor클래스와 같이 특정 코드 블럭(Critiacal Section)을 배타적으로 Locking하는 기능을 가지고 있다. 단, Monitor클래스는 하나의 프로세스 내에서만 사용할 수 있는 반면, Mutex 클래스는 해당 머신의 프로세스간에서도 배타적 Locking을 하는데 사용된다. Mutex 락킹은 Monitor 락킹보다 약 50배 정도 느리기 때문에 한 프로세스내에서만 배타적 Lock이 필요한 경우는 C#의 lock이나 Monitor 클래스를 사용한다. 아래 예제는 MyClass가 외부 프로세스에서도 사용할 수 있다는 가정하에 배타적 Lock으로 뮤텍스를 사용하는 예이다. (실제로는 한 프로세스 내에서 사용할 경우, Monitor를 사용하는 것이 빠른 방식이다) 

    예제

    using System;
    using System.Threading;
    using System.Collections.Generic;   
    
    namespace MultiThrdApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                // 2개의 쓰레드 실행
                Thread t1 = new Thread(() => MyClass.AddList(10));
                Thread t2 = new Thread(() => MyClass.AddList(20));
                t1.Start();
                t2.Start();
    
                // 2개의 쓰레드 실행완료까지 대기
                t1.Join();
                t2.Join();
    
                // 메인쓰레드에서 뮤텍스 사용
                using (Mutex m = new Mutex(false, "MutexName1"))
                {
                    // 뮤텍스를 취득하기 위해 10 ms 대기
                    if (m.WaitOne(10))
                    {
                        // 뮤텍스 취득후 MyList 사용
                        MyClass.MyList.Add(30);
                    }
                    else
                    {
                        Console.WriteLine("Cannot acquire mutex");
                    }
                }
    
                MyClass.ShowList();
            }
        }
    
        public class MyClass
        {
            // MutexName1 이라는 뮤텍스 생성
            private static Mutex mtx = new Mutex(false, "MutexName1");
    
            // 데이타 멤버
            public static List<int> MyList = new List<int>(); 
    
            // 데이타를 리스트에 추가
            public static void AddList(int val)
            {
                // 먼저 뮤텍스를 취득할 때까지 대기
                mtx.WaitOne();
    
                // 뮤텍스 취득후 실행 블럭
                MyList.Add(val);         
       
                // 뮤텍스 해제
                mtx.ReleaseMutex();
            }
    
            // 리스트 출력
            public static void ShowList()
            {
                MyList.ForEach(p => Console.WriteLine(p));
            }
        }
    }
    
    



    프로세스간 Mutex 활용 

    Mutex 활용에 적합한 예로서 흔히 한 머신 내에서 오직 한 응용프로그램(Application)만이 실행되도록 하는 테크닉을 든다. 한 컴퓨터 내 한 프로세스만 뜨게 하기 위해 고유의 Mutex명을 지정할 필요가 있는데, 일반적으로 이를 위해 GUID (globally unique identifier)를 사용한다. 처음 프로세스가 먼저 Mutex를 획득하면 다른 프로세스는 Mutex를 획득할 수 없기 때문에 오직 하나의 프로그램만 머신 내에서 실행되는 것이다. 

    예제

    class Program
    {
        static void Main()
        {
            // Unique한 뮤텍스명을 위해 주로 GUID를 사용한다.
            string mtxName = "60C3D9CA-5957-41B2-9B6D-419DC9BE77DF";
    
            // 뮤텍스명으로 뮤텍스 객체 생성 
            // 만약 뮤텍스를 얻으면, createdNew = true
            bool createdNew;
            Mutex mtx = new Mutex(true, mtxName, out createdNew);
    
            // 뮤텍스를 얻지 못하면 에러
            if (!createdNew)
            {
                Console.WriteLine("에러: 프로그램 이미 실행중");
                return;
            }
    
            // 성공하면 본 프로그램 실행
            MyApp.Launch();
        }
    }

    'Knowledge' 카테고리의 다른 글

    C# 5.0 || await || async  (0) 2018.04.19
    C# version  (0) 2018.04.19
    Working With Thread Local Storage (TLS) in C#  (0) 2018.04.18
    Cross Thread Operations in C#  (0) 2018.04.18
    Aborting Thread Vs Cancelling Task  (0) 2018.04.18


    Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread.  All threads of a process share the virtual address space of the process. The local variables of a function are unique to each thread that runs the function. However, the static and global variables are shared by all threads in the process. With thread local storage (TLS), you can provide unique data for each thread that the process can access using a global index. One thread allocates the index, which can be used by the other threads to retrieve the unique data associated with the index.

    In the .NET Framework version 4, you can use the System.Threading.ThreadLocal<T> class to create thread-local objects.

    System.Threading.ThreadLocal<T>

    where T Specifies the type of data stored per-thread. The ThreadLocal(Of T) type exposes the following members.

    Constructors

    • ThreadLocal(T)- The constructer used to initialize the ThreadLocal(T) instance.
    • ThreadLocal(T)(Tfunc(T))- This constructer is used to initialize the ThreadLocal(Of T)instance with the specified valueFactory function.

    Properties

    • Value- This property is used to get or set the value of this instance for the current thread.
    • IsValueCreated- This property is used to get whether a value is initialized on the current thread.

    Methods

    • Dispose()- This method is used to release all resources used by the current instance of the ThreadLocal(Of T) class.
    • Equals(Object)- This method determines whether the specified Object is equal to the current Object. (Inherited from Object.)
    • Finalize()- This method is used to release the resources used by this ThreadLocal(Of T) instance. (Overrides Object.Finalize.)
    • GetHashCode()- This method serves as a hash function for a particular type. (Inherited from Object.)
    • GetType()- This method gets the Type of the current instance. (Inherited from Object.)
    • MemberwiseClone()- This method is uesd to create a shallow copy of the current Object. (Inherited from Object.)
    • ToString()- This method is uesd to create and return a string representation of this instance for the current thread. (Overrides Object.ToString.)
       

    The .NET Framework provides dynamic data slots that are unique to a combination of thread and application-domain. There are two types of data slots: named slots and unnamed slots. Both are implemented by using the LocalDataStoreSlot structure.

    • To create a named data slot, use the Thread.AllocateDataSlot or Thread.GetNamedDataSlot method. To get a reference to an existing named slot, its name to the GetNamedDataSlot method.
    • To create an unnamed data slot, use the Thread.AllocateDataSlot method.

    For both named and unnamed slots, use the Thread.SetData andThread.GetData methods to set and retrieve the information in the slot. These are static methods that always act on the data for the thread that is currently executing them.

    Named slots can be convenient, because you can retrieve the slot when you need it by ing its name to the GetNamedDataSlot method, instead of maintaining a reference to an unnamed slot. However, if another component uses the same name for its thread-relative storage and a thread executes code from both your component and the other component, the two components might corrupt each other's data. (This scenario assumes that both components are running in the same application domain, and that they are not designed to share the same data.)

    The following example shows how to use ThreadLocal(T):

    using System;
    using System.Threading;
    namespace ThreadLocalStorage
    {
        class akshay
        {
                 public static void WriteError()
            {
                Console.WriteLine("Error number = " +Thread.GetData(Thread.GetNamedDataSlot("ErrNo")));
                Console.WriteLine("Error source = " +Thread.GetData(Thread.GetNamedDataSlot("ErrSource"))
            } 
            public static void SetError()
            {
                Random r = new Random();
                Thread.SetData(Thread.GetNamedDataSlot("ErrNo"), r.Next(100));
                Thread.SetData(Thread.GetNamedDataSlot("ErrSource"),Thread.CurrentThread.Name);
                WriteError();
            }
            public static void Main()
            {
                Thread.AllocateNamedDataSlot("ErrNo");
                Thread.AllocateNamedDataSlot("ErrSource");
                Thread th2 = new Thread(new ThreadStart(SetError));
                th2.Name = "t2";
                th2.Start();
                Thread th3 = new Thread(new ThreadStart(SetError));
                th3.Name = "t3";
                th3.Start();
                Thread.FreeNamedDataSlot("ErrNo");
                Thread.FreeNamedDataSlot("ErrSource");
                Console.Read();
            }
        }
    }

    Output 

    img1.jpg

    We can create thread local storage in the managed environment. Depending on your application, it may be necessary for you to have a static field of a class that is unique for each thread that the class is used in. Doing so is trivially easy in the majority of the cases in C#. If you have a static field that must be thread relative, simply adorn it with the ThreadStaticAttribute attribute. Once you do that, the field will be initialized for each thread that accesses it. Under the covers, each thread is given its own thread relative location to save the value or reference. However, when using references to objects, be careful with your assumptions about the object's creation. The following code shows a pitfall to avoid.

    using System;
    using
     System.Threading;
    namespace ThreadLocalStorage
    {
    public class TLS
        {
            public TLS()
            {
                Console.WriteLine("Creating TLS Class");
            }
         }
     public class TLSFlied
            {
                [ThreadStatic]
                public static TLS Tdata = new TLS();        
            }
      public class EntryPoint
            {
                private static void ThreadFun()
                {
                    Console.WriteLine("Thread {0} starting.....",Thread.CurrentThread.ManagedThreadId);
                    Console.WriteLine("TData for this thread is \"{0}\"",TLSFlied.Tdata);
                    Console.WriteLine("thread {0} exiting",Thread.CurrentThread.ManagedThreadId);
                }
                static void Main()
                {
                    Thread t1 = new Thread(new ThreadStart(EntryPoint.ThreadFun));
                    Thread t2 = new Thread(new ThreadStart(EntryPoint.ThreadFun));
                    t1.Start();
                    t2.Start();
                    Console.Read();
                }
            }
    }

    Output

    img2.jpg

    Resources

    Thread- local storage of data in .NET
    Use Thread Local Storage to Thread Specific Data
    Storing Data in C#
    Windows Azure - Local Storage Feature



    'Knowledge' 카테고리의 다른 글

    C# version  (0) 2018.04.19
    Mutex 클래스  (0) 2018.04.19
    Cross Thread Operations in C#  (0) 2018.04.18
    Aborting Thread Vs Cancelling Task  (0) 2018.04.18
    Task And Thread In C#  (0) 2018.04.18



    Well, if you are working with threads and want to access a control that is created in another thread then you will always face a problem saying that:

    pic1.jpg

    To solve the tiny problem, Here is the solution

    First of all start the thread and assign it a method you want to execute it on.

    Remember, the method you want to assign to the thread should not contain any parameters.

    2.JPG

    Now here is the RunLoop method

    3.JPG

    In the first line we get to know whether the control we want to access is created on the same thread or another thread. If it's created on another thread then it will execute the second line.

    In the second line we create a MethodInvoker with the name of AssignMethodToControl which is a delegate that executes a method that has no parameters.

    In the third line we invoke the MethodInvoker to the Control.

    We have achieved our aim so the method will re-execute and it will loop through condition.

    pic3.jpg
     

    Mohammad Ajmal Amirzad

    Mohammad Ajmal Amirzad

    From Afghanistan is software developer since 2008, Currently working with Chemonics International Inc as System Developer having experience in developing softwares for governmental, educational, healthcare, pharmaceutica... Read more

    http://www.softlogicaf.com/


    'Knowledge' 카테고리의 다른 글

    Mutex 클래스  (0) 2018.04.19
    Working With Thread Local Storage (TLS) in C#  (0) 2018.04.18
    Aborting Thread Vs Cancelling Task  (0) 2018.04.18
    Task And Thread In C#  (0) 2018.04.18
    [.NET] 텍스트 파일에서 읽기  (0) 2018.04.15

    This post is based on one of the questions I answered on StackOverflow, in which the questioner wants to cancel the task when it's taking too long to respond, i.e., taking too much time in execution and returning the result. But, when I tried to provide the answer to that question, I found there is no direct way to cancel the task when making the call to Web Service or making the call to Database to get the data via third-party library ( XenAPI in my case) which is hanging up the application and not allowing it to proceed. To understand this, have a look at the below code.

    1. Var task = Task.Factory.StartNew(()=> CallWebServiceandGetData());  

    The above line of code is creating the task which is making calls to the webservice to get the data. Now, the developer wants to write a code in such a way that if the task takes more than 10 seconds, it gets canceled. However, in TPL library, there is no way to cancel the task, i.e., there is no direct method or there is no other way to make this task cancel because task.Cancel() or task.Abort() like methods do not exist in TPL. The below post is about how a developer can really abort a task.

    Aborting thread vs Cancelling task

    What is the difference between aborting thread and cancelling task.

    Aborting thread 

    System.Treading is a library provided for threading prior to TPL library. (Just to note - old System.Threading is still part of .NET framework but TPL provides more control on Task which is wrapper around thread). In this library, to abort thread there is a method called Abort() available. With the help of this method, a developer can ask execution environment (CLR) to abort the thread. Below is an example code for the same.

    1. Thread newThread = new Thread(() => Console.WriteLine("Test"));  
    2. newThread.Start();  
    3. Thread.Sleep(1000);//sleeping main thread  
    4. newThread.Abort();main thread aborting newly created thread.  

    Cancelling Task 

    In the newer library, TPL (System.Threading.Tasks), there is no direct method which cancels or aborts the underlying thread. But there is a way to cancel a task by using CancellationTokenSource class which allows you to pass the CancellationToken as one of the input parameters when you create the task. (more on this is discussed below). Below is the code for cancelling the task.

    1. var source = new CancellationTokenSource();  
    2.           CancellationToken token = source.Token;  
    3.           Task.Factory.StartNew(() => {   
    4.             for(int i=0;i< 10000;i++)  
    5.             {  
    6.                 Console.WriteLine(i);  
    7.                 if (token.IsCancellationRequested)  
    8.                     token.ThrowIfCancellationRequested();  
    9.             }  
    10.           }, token);  
    11.           source.CancelAfter(1000);  

    So, the above code makes use of CancellationTokenSource and CancellationToken provided by it. In the above code, CancellationTokenSource calls the method CancelAfter which sets taskCancellation flag. This flag is watched inside delegate via IsCancellationRequested property on CancellationToken. And once it sees in the for loop that IsCancellationRequested flag is true, it calls the ThrowIfCancellationRequested() method and cancels the thread.

    So, in simple terms, abort thread allows the developer to abort executing thread and CancellationToken in new TPL library does the same thing, which is called cancelation of task. So basically, newer(TPL) and older(Threading) have different way to cancel/abort thread.

    But one of the major differences between Abort() thread and Cancel task is that Abort() can leave application in an inconsistent state ( on Abort(), the system immediately aborts the thread, not allowing you to perform any operation to put application in consistent state ), especially when doing file operation or doing create/update operation , so it is better to take care when aborting thread or writing code in such a way that the application remains in consistent state. That is one of the reasons TPL come up with Cancellation mechanism, so those who write the code can watch cancellation flag and if it gets true, then they can write the code to put application in consistence state.

    Returning to problem of Cancelling task

    By reading the above section of “Cancellation Task”, one can say there is a provision to cancel task which in turn cancels the thread also and puts the system in consistent state, so it’s a better approach. But, if we now go back to the scenario where a task is created to fetch the data from webService or Database which is taking too much long time, the code will be like below with cancellation mechanism.

    1. var source = new CancellationTokenSource();  
    2. CancellationToken token = source.Token;  
    3. Task.Factory.StartNew(() => {   
    4.     try  
    5.     {  
    6.         //below is third party library(XenAPI) method   
    7.         HTTP_actions.put_import(…//parameter of method);  
    8.         //instead of this there can be database call to get data  
    9.         //which takes too much time   
    10.     }  
    11.     catch (HTTP.CancelledException exception)  
    12.     {  
    13.     }  
    14.     //execution never comes here till above method get complete             
    15.     if (token.IsCancellationRequested)  
    16.         token.ThrowIfCancellationRequested();  
    17.                 
    18. }, token);  
    19. source.CancelAfter(1000);  

    In the above scenario, once the call is made to API method, it never comes back, so control of execution will not return to the application and the code which checks cancellation never get executed till the call returns. Which means the Task does not get cancelled even after 1000 ms and its cancellation flag is set to true for cancellation of task.

    Above scenario is based on Third party API so it might be difficult to understand context. For easy understanding, let us have a look at the below code (just one change here, TaskCompletionSource is used to wrap the underlying task).

    1. static Task<string> DoWork(CancellationToken token)  
    2.         {  
    3.             var tcs = new TaskCompletionSource<string>();  
    4.   
    5.             //comment this whole this is just used for testing   
    6.             Task.Factory.StartNew(() =>  
    7.             {  
    8.                 //Simulate work (usually from 3rd party code)  
    9.                 for (int i = 0; i < 100000; i++)  
    10.                     Console.WriteLine("value" + i);  
    11.   
    12.               //execution never comes here till above for loop or          
    13.               //may be long execution /computation get completed             
    14.                if (token.IsCancellationRequested)  
    15.                     token.ThrowIfCancellationRequested();  
    16.   
    17.                 Console.WriteLine("Task finished!");  
    18.             },token);  
    19.             tcs.SetResult("Completed");  
    20.             return tcs.Task;  
    21.         }  
    22.   public static void Main()  
    23.         {  
    24.             var source = new CancellationTokenSource();  
    25.             CancellationToken token = source.Token;  
    26.             DoWork(token);  
    27.             source.CancelAfter(1000);  
    28.             Console.ReadLine();  
    29. }  

    In the above code, instead of third-party code, I replaced it with the For loop (or consider long calculation task). Now, when execution is going on, the application cannot get a chance to read the cancellation flag which is set up by main thread i.e. from the main method. So, the application is not able to cancel the task until computation is over and control reaches the  point where cancellation flag check is done.

    In both of the scenarios, the major problem is when log computation or long call is going on, the application cannot cancel the task. The Cancellation mechanism provided in TPL does not work and there, we need a solution to cancel this task another way.

    Solution code is,

    1. class Program  
    2. {  
    3.     //capture request running that , which need to be cancel in case  
    4.     // it take more time   
    5.     static Thread threadToCancel = null;  
    6.     static async Task<string> DoWork()  
    7.     {  
    8.         var tcs = new TaskCompletionSource<string>();  
    9.         //comment this whole this is just used for testing   
    10.         await Task.Factory.StartNew(() =>  
    11.         {  
    12.             //Capture the thread  
    13.             threadToCancel = Thread.CurrentThread;  
    14.             //Simulate work (usually from 3rd party code)  
    15.             for (int i = 0; i < 100000; i++)  
    16.                  Console.WriteLine("value" + i);  
    17.            Console.WriteLine("Task finished!");  
    18.         });  
    19.         tcs.SetResult("Completed");  
    20.         return tcs.Task.Result;  
    21.     }  
    22.   
    23.     public static void Main()  
    24.     {  
    25.         var source = new CancellationTokenSource();  
    26.         CancellationToken token = source.Token;  
    27.         DoWork();  
    28.         //another task check for cancellation flag  
    29.         //cancels long running task by calling thread abort method   
    30.         Task.Factory.StartNew(() =>  
    31.         {  
    32.             while (true)  
    33.             {  
    34.                 if (token.IsCancellationRequested && threadToCancel != null)  
    35.                 {  
    36.                     threadToCancel.Abort();//abort long running thread  
    37.                     Console.WriteLine("Thread aborted");  
    38.                     return;  
    39.                 }  
    40.             }  
    41.         });  
    42.         //here 1000 can be replace by miliseconds after which you want to   
    43.         // abort thread which calling your long running method   
    44.         source.CancelAfter(1000);  
    45.         Console.ReadLine();  
    46.     }  
    47. }  

    Comments in the code explain most of the things but let's go into detail about how it’s going to work. Following are the changes in code.

    1. Async/await used to make DoWork method asynchronous
    2. threadToCancel variable in code stores the reference of the thread of underlying Task by calling Thread.CurrentThread. This variable allows to cancel the thread of Task.
    3. One more Task gets created in main which keeps checking the Cancellation flag which is setup by source.CancelAfter(1000); after 1000 miliseconds.
    4. Task created in Main is running While loop with true, which keeps checking Cancellation flag true or not, once it gets true, this task executes the method threadToCancel.Abort(); to abort the underlying thread of long running task.

    So, the real magic part in code is the reference to the underlying thread stored via Thread.CurrentThread. And separate tasks run in the main method to abort long-running task threads when cancellation flag sets to true by CancellationSoruce.

    Pranay Rana

    Pranay Rana

     

    Hey, I am Pranay Rana, working as a Devloper in MNC.  Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 8.2 years now.For me def. of programming is : Programm... Read more

    http://pranayamr.blogspot.com


    'Knowledge' 카테고리의 다른 글

    Working With Thread Local Storage (TLS) in C#  (0) 2018.04.18
    Cross Thread Operations in C#  (0) 2018.04.18
    Task And Thread In C#  (0) 2018.04.18
    [.NET] 텍스트 파일에서 읽기  (0) 2018.04.15
    [SQLite3] 튜토리얼 사이트  (0) 2018.04.15


    This article describes the definition and uses of Task And Thread:

    • What is Task?
    • What is Thread?
    • Why do we need Task?
    • Why do we need Thread?
    • How to implement Task
    • How to implement Thread
      Differences between Task And Thread

    What is Task?

    • .NET framework provides Threading.Tasks class to let you create tasks and run them asynchronously.
    • A task is an object that represents some work that should be done.
    • The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.

      c#

    What is Thread?

    • .NET Framework has thread-associated classes in System.Threading namespace.  
    • A Thread is a small set of executable instructions.
      c#

    Why we need Task:

    1. It can be used whenever you want to execute something in parallel. Asynchronous implementation is easy in a task, using’ async’ and ‘await’ keywords.

    Why we need Thread:

    When the time comes when the application is required to perform few tasks at the same time.

    How to create Task:

    1. static void Main(string[] args) {  
    2.     Task < string > obTask = Task.Run(() => (  
    3.         return“ Hello”));  
    4.     Console.WriteLine(obTask.result);  

    How to create Thread:

    1. static void Main(string[] args) {  
    2.     Thread thread = new Thread(new ThreadStart(getMyName));  
    3.     thread.Start();  
    4. }  
    5. public void getMyName() {} 

    Differences Between Task And Thread

    1. The Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.
    2. The task can return a result. There is no direct mechanism to return the result from a thread.
    3. Task supports cancellation through the use of cancellation tokens. But Thread doesn't.
    4. A task can have multiple processes happening at the same time. Threads can only have one task running at a time.
    5. We can easily implement Asynchronous using ’async’ and ‘await’ keywords.
    6. A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread.
    7. A Task is a higher level concept than Thread.


    'Knowledge' 카테고리의 다른 글

    Cross Thread Operations in C#  (0) 2018.04.18
    Aborting Thread Vs Cancelling Task  (0) 2018.04.18
    [.NET] 텍스트 파일에서 읽기  (0) 2018.04.15
    [SQLite3] 튜토리얼 사이트  (0) 2018.04.15
    [SQLite3] DataType  (0) 2018.04.15


    디자이너 속성에서는 다룰 수 없어.

    탭 컨트롤러에서 동적으로 제거해라!




    • The tabPage.Enabled seems to be working fine, but is marked as "not to be used":

      This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
      This member is not meaningful for this control.

      So you should disable the tab page by disabling every control in the tab. See this for instance.

    • Show / hide

      There is an existing tabPage.Visible property but it does not seem to have any effect. Besides, it is also marked as "not to be used", and msdn advises to remove the tab page from the tab control in order to hide it:

      // Hide the tab page
      tabControl.TabPages.Remove(tabPage1);
      // Show the tab page (insert it to the correct position)
      tabControl.TabPages.Insert(0, tabPage1);



    방법: 텍스트 파일에서 읽기(C# 프로그래밍 가이드)

    이 예제에서는 System.IO.File 클래스의 정적 메서드 ReadAllText 및 ReadAllLines를 사용하여 텍스트 파일의 내용을 읽습니다.

    StreamReader를 사용하는 예제는 방법: 텍스트 파일을 한 번에 한 줄씩 읽기를 참조하세요.

    참고

    이 예제에 사용되는 파일은 방법: 텍스트 파일에 쓰기 항목에서 생성되었습니다.

    예제

    C#
    class ReadFromFile
    {
        static void Main()
        {
            // The files used in this example are created in the topic
            // How to: Write to a Text File. You can change the path and
            // file name to substitute text files of your own.
    
            // Example #1
            // Read the file as one string.
            string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
    
            // Display the file contents to the console. Variable text is a string.
            System.Console.WriteLine("Contents of WriteText.txt = {0}", text);
    
            // Example #2
            // Read each line of the file into a string array. Each element
            // of the array is one line of the file.
            string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");
    
            // Display the file contents by using a foreach loop.
            System.Console.WriteLine("Contents of WriteLines2.txt = ");
            foreach (string line in lines)
            {
                // Use a tab to indent each line of the file.
                Console.WriteLine("\t" + line);
            }
    
            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }


    'Knowledge' 카테고리의 다른 글

    Aborting Thread Vs Cancelling Task  (0) 2018.04.18
    Task And Thread In C#  (0) 2018.04.18
    [SQLite3] 튜토리얼 사이트  (0) 2018.04.15
    [SQLite3] DataType  (0) 2018.04.15
    [WUP] SQLite 관련 Tutorial  (0) 2018.04.14

    + Recent posts