簡體   English   中英

具有線程WCF客戶端的C#Winform應用程序

[英]C# winform application with threaded WCF client

我正在構建一個使用WCF客戶端從服務器檢索數據的應用程序。

我希望對服務的調用是異步的,因為其中許多需要更改UI,並且我不想失去應用程序的響應能力。

我嘗試使用*Completed*Async

ServiceUserClient client = new ServiceUserClient();
client.FindUserCompleted += delegate(object sender, FindUserCompletedEventArgs e)
{
    // here e.Result always fails
};
client.FindUserAsync(text);

在* Completed委托中,我總是收到一個錯誤(遠程主機關閉了連接:我啟用了所有可以找到的日志記錄,但是我仍然不明白為什么會收到這些錯誤)

同步調用始終有效。

我有一個處理所有對該服務的調用的類。

有沒有辦法在線程類之類的內部進行同步調用?

您是否正在設置客戶端綁定以匹配服務器接受的內容?

您還應該嘗試使用WCF測試客戶端進行測試(通常在%Program Files%\\ Microsoft Visual Studio 10.0 \\ Common7 \\ IDE \\ WcfTestClient.exe下)。 如果測試客戶端正常工作,則檢查綁定。

您的電話甚至到達服務器了嗎? 從服務器到客戶端的響應序列化時,我也遇到過類似的錯誤,因此您可能需要檢查一下。 如果您使用服務器,則綁定不是問題,而是序列化問題。 您是否在試圖在服務器上反序列化的數據模型屬性上具有“設置”?

我知道這是沒有答案,但是我來這兒的地方還不夠多,不能發表評論……而我去過你所在的地方,完全感到沮喪。

我最終以這種方式使用BackgroundWorker創建了自己的異步方法(可能不是最好的方法,但是它可以工作):

// this is the click event on my search button
private void FindUser_Click(object sender, EventArgs e)
{
    this.UserListSearch.Enabled = false;
    this.UserListSearch.Items.Clear();
    Model.FindUser(FindText.Text.ToUpper(), userlist =>
    {
        foreach (User u in userlist)
        {
            ListViewItem item = new ListViewItem(u.UserName);
            item.Name = u.UserName;
            item.SubItems.Add(u.Description);
            this.UserListSearch.Items.Add(item);
        }
        this.UserListSearch.Enabled = true;
    });
}

// this is the function I call when I need async call
public void FindUser(string text, Action<User[]> callback)
{
    CreateBackgroundWorker<User[]>(() =>
        {
            ServiceUsersClient client = new ServiceUsersClient();
            var results = client.FindUser(text);
            client.Close();
            return results;
        }, callback);
}

// this is my utility function to create a bgworker "on demand"
private void CreateBackgroundWorker<T>(Func<T> dowork, Action<T> callback)
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (sender, args) =>
    {
        T result = dowork.Invoke();
        (callback.Target as Form).Invoke(callback, result);
    };
    worker.RunWorkerAsync();
}

暫無
暫無

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

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