2011-11-02 2 views
0

위임자를 배우려고했습니다. 방금 버튼, 레이블 및 확인란을 만들었습니다. 확인란을 클릭하면 시간 형식이 변경됩니다. 버튼을 클릭하면 그에 따라 날짜가 인쇄됩니다. 다른 스레드를 사용하는, 즉 asynchromous 대리자를 사용하려고 할 때, 나는 오류크로스 스레드 작업이 유효하지 않습니다. 비동기 위임자 오류

public delegate void AsyncDelegate(bool seconds); 

public partial class Form1 : Form 
{ 
    AsyncDelegate ad; 
    TimeZ t = new TimeZ(); 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

private void btn_async_Click(object sender, EventArgs e) 
    { 

     ad = new AsyncDelegate(t.GetTime); 
     AsyncCallback acb = new AsyncCallback(CB); 
     if (chk_sec.Checked) 
     { 
      ad.BeginInvoke(true, acb, null); 
     } 
     else 
      ad.BeginInvoke(false, acb, null); 


    } 
    public void CB(IAsyncResult ar) 
    { 
     t.Tim = ar.ToString(); 
     ad.EndInvoke(ar); 
     lbl_time.Text = t.Tim; 
    } 

와 내가 Timez 위 익숙해 또 다른 클래스 라이브러리에 갇혀 있어요.

Cross-thread operation not valid: Control 'lbl_time' accessed from a thread other than 
    the thread it was created on. 

는 u는이 문제를 해결하는 방법에 나를 도와 드릴까요 : 내가 프로그램을 실행할 때이 오류가 그러나 나는이 프로젝트

public class TimeZ 
{ 
    private string tim; 
    public string Tim 
    { 
     get 
     { 
      return tim; 
     } 
     set 
     { 
      tim = value; 
     } 
    } 
    public string GetTime(bool seconds) 
    { 
     if (seconds) 
     { 
      return DateTime.Now.ToLongTimeString(); 
     } 
     else 
      return DateTime.Now.ToShortTimeString(); 
    } 
} 

에의 참조를 추가?

+0

누군가 내 마음을 어렴풋이 보네요. 이 코드로 무엇을하려하고 있습니까? –

답변

4

양식 스레드가 아닌 스레드에서 양식에 액세스하거나 속성 및 메서드를 제어 할 수 없습니다.

윈도우에서 각 윈도우는 윈도우를 생성 한 스레드에 바인딩됩니다.

Control.BeginInvoke 또는보다 유용한 System.Threading.SynchronizationContext 클래스를 사용하면됩니다.

는 예를 들어 동기화 컨텍스트를 통해 양식 스레드의 다른 비동기 대리자를 게시해야

http://msdn.microsoft.com/it-it/library/system.threading.synchronizationcontext(v=vs.95).aspx 그것은 의미 http://msdn.microsoft.com/it-it/library/0b1bf3y3(v=vs.80).aspx

참조하십시오. 당신은 그러나 시간을 인쇄하는 비동기 콜백이 필요한 이유

public partial class Form1 : Form 
{ 
    AsyncDelegate ad; 
    TimeZ t = new TimeZ(); 

    // Our synchronization context 
    SynchronizationContext syncContext; 

    public Form1() 
    { 
     InitializeComponent(); 

     // Initialize the synchronization context field 
     syncContext = SynchronizationContext.Current; 
    } 

    private void btn_async_Click(object sender, EventArgs e) 
    { 

     ad = new AsyncDelegate(t.GetTime); 
     AsyncCallback acb = new AsyncCallback(CB); 
     if (chk_sec.Checked) 
     { 
      ad.BeginInvoke(true, acb, null); 
     } 
     else 
     { 
      ad.BeginInvoke(false, acb, null); 
     } 
    } 

    public void CB(IAsyncResult ar) 
    { 
     // this will be executed in another thread 
     t.Tim = ar.ToString(); // ar.ToString()???? this will not give you the time for sure! why? 
     ad.EndInvoke(ar); 

     syncContext.Post(delegate(object state) 
     { 
      // This will be executed again in form thread 
      lbl_time.Text = t.Tim; 
     }, null); 
    } 

모르겠어요 :) 정말 이유를 알고하지 않습니다, 그냥 몇 가지 테스트 코드입니다 생각.

+0

안녕 살바토레, 위의 문제를 해결하는 방법에 나를 도울 수 있겠 니 .... – user838359

+0

그냥 코드를 편집하여 그것을 시도해보십시오. –

+0

내가 어디로 잘못 가고 있는지 모르지만, 지금은 System.Remote.Remoting.Messaging.AsyncResult가 아니라 현재 날짜를 인쇄합니다. – user838359

관련 문제