簡體   English   中英

如何從其他線程(.net緊湊框架)正確創建控件,而不引用其他控件?

[英]How to create a control properly from other thread (.net compact framework), with no reference to other control?

我的代碼運行在與UI不同的線程中,它必須創建一個控件(窗體)。 但是,我沒有從UI的任何控件的引用(這樣,我可以使用myControl.Invoke( methodThatAddsControlToUI ) )。 有沒有辦法在.net 緊湊框架中做到這一點?

如果可能的話,我會對不使用對其他控件的引用的解決方案感興趣(例如,跟蹤所有創建的表單不會是一個好的解決方法,因為我的代碼將在庫中)。 在完整的框架版本中,有Application.OpenForms屬性,但這不會在CF中退出。

編輯:

這樣做的主要目的是在UI線程上調用一個方法:

class Worker
{
    public MyMethod()
    {
        // I need to call a method on the UI (this code doesn't run in the UI thread), 
        // but I don't have any field  in this object holding an UI control
        // value. So, I can't write myControlField.Invoke(...),
        // but I still need to call a method on the UI thread
    }
}

有什么建議么?

從庫中無法保證您的線程上下文,因此您最安全的選擇是讓消費者提供調用者並將其留給他們以確保它是在適當的上下文中創建的。 像這樣的模式:

class Foo
{
    private Control m_invoker;

    public Foo()
        : this(null)
    {
    }

    public Foo(Control invoker)
    {
        if (invoker == null)
        {
            // assume we are created on the UI thread, 
            // if not bad things will ensue
            m_invoker = new Control();
        }
        else
        {
            m_invoker = invoker;
        }
    }

    public void Bar()
    {
        m_invoker.Invoke(new Action(delegate
        {
            // do my UI-context stuff here
        }));
    }
}

如果這不是一個真正的答案,我很抱歉,但我認為這可能會有所幫助:

WinForms之所以采用這種方法 - 使用Control或Form引用來訪問使您能夠在UI線程上運行代碼的Invoke方法 - 是因為您必須在UI線程中運行代碼的唯一原因是您將要編寫/更改UI組件的狀態。

當然,如果要這樣做,則必須引用UI組件。 所以你可以訪問它的Invoke方法。 我想不出除了修改可視元素之外你必須從組件訪問UI線程的任何其他原因。

它必須調用...但是調用必須等待主線程我的意思是你沒有得到這種方式的錯誤但是如果你想同時進行多個進程只是創建一個以上的線程,那么這並非行得並行

Thread thread = new Thread(new delegate_method(method));
thread.start ();
Thread thread2 = new Thread(new delegate_method(method2));
thread.start ();

同時處理兩個進程

    void method ()
{
//do something here -- working background Remember can not control any UI control from here
finish_thread()
}

void method2 ()
{
//do something here -- working background Remember can not control any UI control from here
finish_thread()
}

void finish_thread()
{
if(invoke.Required)
{
//Here you have to call delegate method here with UI
BeginInvoke(new delegate_method(finish_thread));
}
else
{
//Now you can control UI thread from here and also you finished background work
//Do something working with UI thread
textBox.Text = "";
}
}
//Declare this in class
public delegate void delege();

//Write this lines when you want to background thread start
    Thread thread = new Thread(new ThreadStart(() => {
    //Do what you what with backgorund threading , can not use any interface comand here
         BeginInvoke(new delege(() => { 
           //Do here any main thread thread job,this can do interface and control jobs without any error 
         }));
    }));
    thread.Start();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM