티스토리 뷰

Code/C#

[C#] Thread & FileStream 사용 예제

Hide Code 2007. 12. 7. 20:46
이 예제는 앞의 예제를 약간 변형한 것이다.

Thread와 FileStream을 동시에 사용해보았다.

FileStream 에서 FileMode.Append, FileAccess.Write, FileShare.Write 를 사용해서 복수개의 Thread가 File에 접근할 수 있도록했다.

FileShare.Write 옵션을 사용하지 않으면, Exception이 발생한다.

이 부분을 이해하는 것이 중요하다.

아래는 코드이다.



using System;
using System.Threading;
using System.IO;
using System.Text;

public class NameUsingThread
{
   private int time;
   private Thread thread;

   public NameUsingThread(String n, int t)
   {
       time = t;
       thread = new Thread(new ThreadStart(Run));
       thread.Name = n;
       thread.Start();
   }

   public void Run()
   {
       for (int i = 1; i <= 5; i++)
       {
           using (FileStream fs = new FileStream("sample.txt",
               FileMode.Append, FileAccess.Write, FileShare.Write))
           {
               AddText(fs, thread.Name + " " + i + Environment.NewLine);
               Thread.Sleep(time);
           }
       }
   }

   private void AddText(FileStream fs, string value)
   {
       byte[] info = new UTF8Encoding(true).GetBytes(value);
       fs.Write(info, 0, info.Length);
       fs.Flush();
   }

   public static void Main()
   {
       NameUsingThread bonnie = new NameUsingThread("Bonnie", 500);
       NameUsingThread clyde = new NameUsingThread("Clyde", 1000);

       Thread.CurrentThread.Name = "Main";
       
       for (int i = 1; i <= 5; i++)
       {
           Console.WriteLine(Thread.CurrentThread.Name + " " + i);
           Thread.Sleep(1500);
       }
   }
}




아래는 파일에 저장된 결과이다.

Bonnie 1
Clyde 1
Bonnie 2
Bonnie 3
Clyde 2
Bonnie 4
Clyde 3
Bonnie 5
Clyde 4
Clyde 5



'Code > C#' 카테고리의 다른 글

[C#] C# 2.0 스타일 Thread 사용법과 예제  (0) 2007.12.08
[C#] Thread 샘플 코드 4  (0) 2007.12.08
[C#] Thread 샘플 코드 3  (0) 2007.12.07
[C#] Thread 샘플 코드 2  (0) 2007.12.07
[C#] Thread 샘플 코드 1  (0) 2007.12.07
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/09   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함